Skip to content

API reference

All public names are re-exported from wxdiagram; the sections below are generated from the docstrings with mkdocstrings. If you are porting from wx.lib.ogl, also read the migration guide.

At a glance

Area Types
Canvas ShapeCanvas, Diagram
Basic shapes Shape, RectangleShape, EllipseShape, CircleShape, PolygonShape, LinesShape
Interactive shapes Block, ResizableRectangleShape, ConnectableEllipseShape, DividedShape, CompositeShape, GroupShape, SelectableTextShape
Edges LineShape, ConnectionShape, ArrowHead
Bitmaps BitmapShape, ResizableBitmapShape
Mixins Selectable, Resizeable, Connectable, Attributable
Routing wxdiagram.routing.route_edge, LineShape.SetRouteMode; experimental router injection: RouteRequest, RouteResult, BaseRouter, DefaultRouter, LineShape.SetRouter, ShapeCanvas.RouteEdges
Layout LayoutNode, LayoutEdge, LayoutResult, SpringLayout, register_layout, Diagram.ApplyLayout, ShapeCanvas.ApplyLayout; metrics: count_crossings, total_edge_length, reduce_crossings
Persistence wxdiagram.persistence.save, wxdiagram.persistence.load

Canvas

ShapeCanvas

The scrolled window that owns selection, zoom/pan, routing defaults and repainting. Pass it a Diagram with SetDiagram().

wxdiagram.ShapeCanvas

Bases: ScrolledWindow

AddShape(shape, addAfter=None)

InsertShape(shape, index=0)

AppendShape(shape)

DeleteShape(shape)

AddImage(path, max_size=None, center=True, send_to_back=True, shape_factory=None, **shape_kwargs)

Load an image, add it as a resizable bitmap shape and return it.

max_size=(w, h) scales large images down (preserving aspect ratio). center=True places it in the middle of the current viewport. send_to_back=True puts imported images behind the diagram. shape_factory lets applications supply a shape subclass (for example one mixing in their own event handler).

join_shapes(fromShape, toShape, edge_type='association')

Connect two shapes with an attached line.

The edge is a LineShape attached via AddLine (with the default attachment mode), so its endpoints are clipped to the shapes' perimeters on the centre-to-centre ray and are recomputed whenever either shape moves. The edge therefore always leaves and enters through whichever sides face each other, from any direction.

Port nodes are only the drag handles a connection is started from; they never constrain a finished edge. edge_type is accepted for compatibility (subclasses such as pynsource's UmlCanvas override this to build richer edges) but the base line is unadorned. Returns the created line so callers can label it.

select(item=None)

deselect(item=None)

getSelectedShapes()

update_virtual_size()

Recompute the virtual size from the bounds of all shapes.

ZoomIn(step=None, anchor=None)

Zoom in (increase the scale by step).

ZoomOut(step=None, anchor=None)

Zoom out (decrease the scale by step).

ZoomTo(scale, anchor=None)

Zoom directly to scale (clamped to the min/max zoom range).

ZoomReset()

Zoom back to 100%.

ZoomToFit(margin=None)

Zoom so all shapes fit inside the viewport.

CenterOn(diagram_x, diagram_y)

Scroll so the diagram position is centred in the viewport.

Snap(x, y)

Snap a diagram coordinate to the grid (if snapping is enabled).

ExportPng(path, scale=1.0, margin=0)

Render the diagram to a PNG file and return True on success.

Selection handles, guides and the marquee are not included. scale multiplies diagram units and margin adds a border in output pixels.

getContentBounds()

Return (max_x, max_y) for the content the canvas should navigate.

Subclasses can override this to exclude shapes that should not influence zoom-to-fit (for example, edges or decoration). The default covers every top-level shape and its composite children.

getContentOrigin()

Return (min_x, min_y) for the content the canvas should navigate.

This is the top-left corner of the scrollable area. By default it covers every top-level shape and its composite children, so content can extend to negative diagram coordinates and still be reached by scrolling. Subclasses overriding :meth:getContentBounds may override this too.

snapshot_state()

Return a comparable snapshot of the diagram state.

Applications with their own model can override this and restore_state() with an opaque snapshot object; the undo stack only compares snapshots for equality. The default snapshot covers geometry, visibility, style, names, line control points, composite membership and edge endpoints, so colour edits and group/ungroup round-trip through undo/redo.

restore_state(snapshot)

Restore a snapshot produced by snapshot_state().

undo()

redo()

duplicate_selected(offset=(20, 20))

Copy selected top-level shapes and select the copies.

delete_selected()

Delete every selected shape as one undoable operation.

Attached edges are deleted with the shapes they connect, and their references are removed from the remaining endpoint. Otherwise a deleted shape would leave a floating edge behind.

group_selected()

Group the selected top-level shapes into a :class:GroupShape.

Attached lines are left top-level so edges keep following their endpoints. Returns the new group, or None when fewer than two groupable shapes are selected.

ungroup_selected()

Ungroup selected groups, returning released children to the canvas.

bring_to_front(shapes=None)

Move the given shapes (default: selection) to the top of the z-order.

send_to_back(shapes=None)

Move the given shapes (default: selection) to the bottom of the z-order.

bring_forward(shapes=None)

Move the given shapes one step up in the z-order.

send_backward(shapes=None)

Move the given shapes one step down in the z-order.

Canvas callbacks you can set (plain attributes, not methods):

Attribute Purpose
onSelectionChanged optional fn(canvas) fired by select() / deselect()

Canvas settings you are likely to tune (class or instance attributes):

Attribute Default Purpose
autoVirtualSize True keep the scrollbars in sync with the shapes
zoomInputEnabled True handle Ctrl+wheel and pinch
panOnDrag True Alt/Space/middle-drag pans
emptyDragMode "marquee" plain drag on empty canvas: "marquee" or "pan"
zoomAnchor "mouse" "mouse", "selection" or "center"
bringClickedShapeToFront True raise shapes when clicked
showGrid False draw the diagram grid
snapToGrid False snap drags to the grid
alignmentGuides True magnetic guides to other shapes
bufferedPainting False use AutoBufferedPaintDC
handleFillColour / handleOutlineColour dark/white resize handle chrome
portFillColour / portOutlineColour white/grey connection dot chrome
marqueePenColour blue marquee selection pen
gridColour / guideColour light grey / magenta grid and alignment guide pens
connectionPenColour blue-grey temporary line while dragging a connection
edgePenColour / edgePenWidth None / 2 default pen for edges created by join_shapes
showDropPorts True draw legacy drop ports while connecting
WHEEL_SCROLL_PIXELS 20 wheel pixels per notch (Windows/Linux)
WHEEL_SCROLL_PIXELS_MACOS 1.0 multiplier on wxOSX's precise deltas
PAN_START_THRESHOLD 3 pixels before a drag becomes a pan
DRAG_TOLERANCE 3 pixels before a shape move/resize starts

Diagram

The shape list plus grid/snap and save/load helpers.

wxdiagram.Diagram

SetGridSpacing(spacing)

Set the grid spacing in diagram units (0 or less disables it).

GetGridSpacing()

Return the grid spacing in diagram units.

SetSnapToGrid(snap)

Turn snapping to the grid on or off.

GetSnapToGrid()

Return whether dragging snaps to the grid.

Snap(x, y)

Return (x, y) rounded to the nearest grid point.

Save(path)

Save the diagram to a JSON file (see :mod:wxdiagram.persistence).

Load(path) classmethod

Load a diagram from a JSON file (see :mod:wxdiagram.persistence).

SetCanvas(canvas)

Set the shape canvas associated with this diagram.

GetCanvas()

Return the shape canvas associated with this diagram.

ShowAll(show)

Call Show for each shape in the diagram.

Clear(dc)

Clear the device context, as classic OGL does.

Use :meth:DeleteAllShapes to remove the diagram's shapes.

FindShape(shape_id)

Return the shape with the given id, or None.

Searches top-level shapes and composite children.

ApplyLayout(engine='spring', options=None, on_step=None)

Run a layout engine and move top-level shapes to its positions.

engine is a registered layout name or an engine instance with a layout(nodes, edges, ...) method (see :mod:wxdiagram.layout). Positions are top-left coordinates applied with move_to; attached lines then have their endpoints re-clipped. Full obstacle routing happens in :meth:ShapeCanvas.ApplyLayout, which has canvas context. Returns the :class:LayoutResult.

Shapes

Shape

Base class: point lists (x, y), pen/brush, attached lines, canvas attachment, copying. Shape also owns AddLine / RemoveLine, so any shape (not just rectangles) can be the source of an attached edge.

wxdiagram.Shape

Bases: ShapeEvtHandler

GetName()

Return the user-editable name metadata (may be empty).

SetName(name)

Set the user-editable name metadata.

GetFillColour()

Return the fill colour as a wx.Colour.

SetFillColour(colour)

Set the fill colour (name, hex string or wx.Colour).

GetPenColour()

Return the outline colour as a wx.Colour.

SetPenColour(colour)

Set the outline colour (name, hex string or wx.Colour).

GetPenWidth()

Return the outline width in pixels.

SetPenWidth(width)

Set the outline width in pixels (minimum 1).

SetAttachmentMode(mode)

Set the attachment mode (see :meth:GetAttachmentMode).

GetAttachmentMode()

Return the attachment mode (default ATTACHMENT_MODE_NONE).

Copy()

Return a detached copy of this shape.

wx objects (fonts, pens, brushes, bitmaps) are shared, not deep-copied: they are native handles and cannot be pickled. Geometry and region text are copied, while attached lines and the graph-node back-reference are cleared so a duplicate starts clean.

SetId(shape_id)

Set the integer identifier for this shape.

GetId()

Return the integer identifier for this shape.

AssignNewIds()

Assign a new id to this shape and any composite children.

SetLayoutFixed(fixed)

Exclude this shape from layout engines that honour the fixed flag.

IsLayoutFixed()

Return whether layout engines should leave this shape in place.

GetX()

Get the x position of the centre of the shape.

GetY()

Get the y position of the centre of the shape.

SetX(x)

Set the x position of the shape.

Parameters:

Name Type Description Default
`x`

the x position

required

SetY(y)

Set the y position of the shape.

Parameters:

Name Type Description Default
`y`

the y position

required

GetBoundingBoxMax()

Get the maximum bounding box for the shape, taking into account external features such as shadows.

GetBoundingBoxMin()

Get the minimum bounding box for the shape, that defines the area available for drawing the contents (such as text).

Must be overridden.

GetBackgroundPen()

Return pen of the right colour for the background.

GetBackgroundBrush()

Return brush of the right colour for the background.

Delete()

Fully disconnect this shape from parents, children, the canvas, etc.

ClearAttachments()

Clear internal custom attachment point shapes (of class :class:~lib.ogl.AttachmentPoint)

ClearText(regionId=0)

Clear the text from the specified text region.

Parameters:

Name Type Description Default
`regionId`

the region identifier

required

Erase(dc)

Erase the shape.

Does not repair damage caused to other shapes.

EraseContents(dc)

Erase the shape contents, that is, the area within the shape's minimum bounding box.

Move(dc, x, y, display=True)

Move the shape to the given position.

Parameters:

Name Type Description Default
`dc`

the device context

required
`x`

the x position of the shape's centre

required
`y`

the y position of the shape's centre

required
`display`

if True redraw

Use :meth:MoveTo when working with top-left coordinates.

required

MoveTo(dc, x, y, display=True)

Move the shape so its top-left corner is at (x, y).

Unlike :meth:Move, which takes the centre position, this matches the coordinate convention used by layouts and diagram persistence. Attached lines are refreshed via :meth:MoveLinks.

Parameters:

Name Type Description Default
`dc`

the device context (may be None)

required
`x`

the x position of the shape's top-left corner

required
`y`

the y position of the shape's top-left corner

required
`display`

accepted for compatibility; drawing is left to the caller

required

Redraw all the lines attached to the shape.

Refresh every line attached to this shape.

This is the base implementation: any shape (rectangle, ellipse, polygon, composite) can carry attached edges, so moving a target shape must re-route them too - not only rectangles.

AddLine(line, other, attachFrom=0, attachTo=0, positionFrom=-1, positionTo=-1)

Add a line between this shape and the given other shape.

Lines are stored on both endpoint shapes. This lives on Shape (rather than only on rectangles) so any connectable shape - ellipses, polygons, groups - can be the source of an attached edge.

Parameters:

Name Type Description Default
`line`

an instance of :class:wxdiagram.LineShape

required
`other`

the other shape, an instance of :class:Shape

required
`attachFrom`

the attachment from point

required
`attachTo`

the attachment to point

required
`positionFrom`

the from position

required
`positionTo`

the to position

required

RemoveLine(line)

Remove the given line from the shape's list of attached lines.

ResetControlPoints()

Shape, RectangleShape, CommentShape(RectangleShape) all didn't have this method so I defined it here, doing nothing, to stop failed calls to it.

SetCanvas(theCanvas)

Set the canvas, identical to Shape.Attach.

Parameters:

Name Type Description Default
`theCanvas`

an instance of :class:~lib.ogl.Canvas

required

GetCanvas()

Get the internal canvas.

Show(show)

Set whether this shape (and any composite children) is drawn.

IsShown()

Return True when this shape is in a visible state.

GetParent()

Get the parent of this shape, if it is part of a composite.

SetParent(p)

Set the parent

Parameters:

Name Type Description Default
`p`

the parent

required

GetTopAncestor()

Return the top-most ancestor of this shape (the root of the composite).

GetPerimeterPoint(x1, y1, x2, y2)

Get the point at which the line from (x1, y1) to (x2, y2) hits the shape.

Parameters:

Name Type Description Default
`x1`

the x1 position

required
`y1`

the y1 position

required
`x2`

the x2 position

required
`y2`

the y2 position

required

Returns:

Type Description

False if the line doesn't hit the perimeter.

Connection UX: connectable shapes show four corner resize handles and four round side dots. Connectable.connection_points() returns the dots clipped to the real perimeter (triangles use their sloping edges). Drag a dot and release over another connectable shape body to create an attached edge; showDropPorts enables the legacy drop ports (drawn in the same round style).

RectangleShape

wxdiagram.RectangleShape

Bases: Shape

AddText(string)

Add a line of text to the shape's default text region.

OnDrawContents(dc)

The draw contents handler.

OnDraw(dc)

Use the draw handler instead - avoid recursion mishaps calling both.

GetBoundingBoxMin()

Get the bounding box minimum.

SetSize(x, y, recursive=False)

Set the size.

Parameters:

Name Type Description Default
`x`

the width

required
`y`

the height

required
`recursive`

not used

required

ClearRegions()

Clear the ShapeRegions from the shape.

AddRegion(region)

Add a region to the shape.

GetRegions()

Get the list of ShapeRegions.

SetDefaultRegionSize()

Set the default region to be consistent with the shape size.

SetAttachmentSize(w, h)

Set the attachment size.

Parameters:

Name Type Description Default
`w`

width

required
`h`

height

required

Redraw all the lines attached to the shape.

SetCentreResize(cr)

Specify whether the shape is to be resized from the centre (the centre stands still) or from the corner or side being dragged (the other corner or side stands still).

GetCentreResize()

True if the shape is to be resized from the centre (the centre stands still), or False if from the corner or side being dragged (the other corner or side stands still)

SetDraggable(drag, recursive=False)

Set the shape to be draggable or not draggable.

Parameters:

Name Type Description Default
`drag`

if True make shape draggable

required
`recursive`

if True recurse through children

required

FormatText(dc, s, i=0)

Reformat the given text region; defaults to formatting the default region.

Parameters:

Name Type Description Default
`dc`

the device contexr

required
`s` str

the text string

required
`i` int

the region identifier

required

AddLine(line, other, attachFrom=0, attachTo=0, positionFrom=-1, positionTo=-1)

Add a line between this shape and the given other shape.

Kept as a thin delegate for backwards compatibility; the implementation now lives on :class:Shape.

RemoveLine(line)

Remove the given line from the shape's list of attached lines.

SetAttachmentMode(mode)

Set the attachment mode.

Parameters:

Name Type Description Default
`mode`

if True attachment points will be significant when drawing lines to and from this shape. If False lines will be drawn as if to the centre of the shape.

required

GetAttachmentMode()

Get the attachment mode.

See :meth:Shape.SetAttachmentMode

GetPerimeterPoint(x1, y1, x2, y2)

Get the perimeter point.

Parameters:

Name Type Description Default
`x1`

???

required
`y1`

???

required
`x2`

???

required
`y2`

???

required

Block

A labelled, connectable rectangle (the common "box" shape).

wxdiagram.Block

Bases: RectangleShape, Connectable, Resizeable, Selectable, Attributable

SetLabelColour(colour)

Set the label colour (a colour name or a wx.Colour).

AddText(string)

Add a line of text to the shape's default text region.

ResizableRectangleShape

wxdiagram.ResizableRectangleShape

Bases: RectangleShape, Selectable, Resizeable

A plain rectangle that can be selected and resized.

EllipseShape

wxdiagram.EllipseShape

Bases: Shape

GetBoundingBoxMin()

Return (width, height) of the ellipse's bounding box.

draw(dc)

The draw handler.

GetPerimeterPoint(x1, y1, x2, y2)

Clip the (x2, y2) -> centre ray to the ellipse perimeter.

ConnectableEllipseShape

wxdiagram.ConnectableEllipseShape

CircleShape

A connectable ellipse that stays circular: proportional resize only, with four corner handles.

wxdiagram.CircleShape

Bases: EllipseShape, Connectable, Resizeable, Selectable, Attributable

An ellipse that stays circular while resizing.

Single-handle drags are always proportional and only the four corner handles are shown. Group resizes may still scale x and y independently; use an ellipse if the result must stay non-square.

PolygonShape

A closed polygon; hit-testing covers its interior.

wxdiagram.PolygonShape

Bases: LinesShape

A closed polygon defined by points offset from its centre.

__init__()

The ogl-like version expects points to be added later via Create().

Create(the_points=None)

Set the polygon points from a list of (x, y) tuples.

ClearPoints()

Clear the points.

HitTest(x, y)

Interior hit test (ray casting), so the whole polygon is clickable.

GetBoundingBoxMin()

Return (width, height) of the vertex bounding box.

GetX()

Return the x position of the bbox centre.

GetY()

Return the y position of the bbox centre.

GetPerimeterPoint(x1, y1, x2, y2)

Clip the centre -> target ray to the polygon's edges.

move_handle(index, dx, dy, free_aspect=False, from_center=False)

Scale all vertices from the bounding box.

index selects a corner/edge handle using the same layout as rectangles (see RECT_HANDLES); the opposite side stays fixed unless from_center is set. Corner drags stay proportional unless free_aspect is set. Returns True (handled).

draw(dc)

Draw a closed polygon.

LinesShape.draw draws an open polyline, so the last edge back to the first point would be missing.

LinesShape

An open polyline through a list of points.

wxdiagram.LinesShape

Bases: Shape, Resizeable

DividedShape

A rectangle split into regions (the UML class-box look).

wxdiagram.DividedShape

Bases: RectangleShape, Connectable, Resizeable, Selectable, Attributable

A :class:DividedShape is a rectangle with a number of vertical divisions. Each division may have its text formatted with independent characteristics, and the size of each division relative to the whole image may be specified.

__init__(w, h)

Default class constructor.

Parameters:

Name Type Description Default
`w`

width of rectangle

required
`h`

heigth of rectangle

required

SetFont(the_font, regionId=0)

Set the font for the specified text region.

Parameters:

Name Type Description Default
`the_font`

an instance of :class:wx.Font ???

required
`regionId`

the region identifier

required

draw(dc)

The draw handler.

OnDrawContents(dc)

The draw contents handler.

SetSize(w, h, recursive=True)

Set the size.

Parameters:

Name Type Description Default
`w`

width of rectangle

required
`h`

heigth of rectangle

required
`recursive`

not implemented

required

SetRegionSizes()

Set all region sizes according to proportions and this object total size.

ResetControlPoints()

Reset the control points.

:note: May only have the region handles, (n - 1) of them

ResetMandatoryControlPoints()

Reset the mandatory control points.

CompositeShape

A rectangle that owns child shapes and constraints. Resizing the frame scales the children with it.

wxdiagram.CompositeShape

Bases: RectangleShape, Selectable, Resizeable

A rectangle whose child shapes move and scale with it.

Children can also be constrained in layout; resizing the frame scales the children proportionally (their fonts are unchanged), and any constraints are re-evaluated afterwards.

GetConstraints()

Return the constraints owned by this composite.

move_handle(index, dx, dy, free_aspect=False, from_center=False)

Resize the frame and scale the children with it.

CalculateSize()

Resize and reposition the composite to enclose its children.

RemoveChildFromConstraints(child)

Remove child from any constraint that references it.

A constraint whose constraining object is the child is removed entirely; otherwise the child is removed from the constrained list. Empty constraints are dropped.

DeleteConstraintsInvolvingChild(child)

Alias for :meth:RemoveChildFromConstraints.

Constrain()

Evaluate the constraints once. Returns True if anything moved.

Recompute(maxIterations=500)

Evaluate constraints until stable (or maxIterations is reached).

Returns True if the constraints settled, False if it gave up.

GroupShape

A composite that draws only its children. Use ShapeCanvas.group_selected() / ungroup_selected(); attached lines stay top-level so edges keep following their endpoints.

wxdiagram.GroupShape

Bases: CompositeShape

A composite that draws only its children (no opaque frame).

The frame still owns the resize handles: dragging a handle scales the children with it, exactly like :class:CompositeShape. Attached lines are never group children; they stay top-level so edges keep following their endpoint shapes.

BitmapShape / ResizableBitmapShape

wxdiagram.BitmapShape

Bases: RectangleShape, Selectable, Resizeable

The :class:wx.BitmapShape class draws a bitmap (non-resizable).

__init__()

Default class constructor.

draw(dc)

The draw handler.

SetSize(w, h, recursive=True)

Set the size.

Parameters:

Name Type Description Default
`w`

the width

required
`h`

the heigth

required
`recursive`

not used

required

GetBitmap()

Get the associated bitmap.

SetBitmap(bitmap)

Set the associated bitmap.

:note: You can delete the bitmap from the calling application, since reference counting will take care of holding on to the internal bitmap data.

Parameters:

Name Type Description Default
`bitmap`

a :class:wx.Bitmap instance

required

SetFilename(f)

Set the bitmap filename.

Parameters:

Name Type Description Default
`f` str

the bitmap file name

required

GetFilename()

Return the bitmap filename.

wxdiagram.ResizableBitmapShape

Bases: BitmapShape

A bitmap shape whose displayed bitmap is rescaled when it is resized.

ResetSize()

Restore the bitmap's original dimensions.

move_handle(index, dx, dy, free_aspect=False, from_center=False)

Resize from a drag handle, keeping the opposite corner fixed.

Only the dragged point moves: changing the size and then re-deriving the far edge (as SetSize does) would re-anchor the shape at its top-left and quantise the drag, so the image lags behind the mouse. The resize is proportional unless free_aspect is set; with from_center both sides move symmetrically.

TextShape / SelectableTextShape

wxdiagram.TextShape

Bases: Shape

A non-interactive text label.

Useful for section headings and annotations. It is not hit-testable, so it never gets in the way of selecting the shapes around it.

wxdiagram.SelectableTextShape

Bases: TextShape, Selectable

A text caption that can be selected and moved (no resize handles).

Edges

LineShape

Attached or free lines, arrowheads, splines, bends, labels and routing modes.

wxdiagram.LineShape

Bases: LineShapeBase, Selectable, Resizeable

AddArrow(type, end=ARROW_POSITION_END, size=10.0, xOffset=0.0, name='', mf=None, arrowId=-1)

Add an arrow (or annotation) to the line.

Parameters:

Name Type Description Default
`type`

an arrow head type, one of the following

======================================== ================================== Arrow head type Description ======================================== ================================== ARROW_HOLLOW_CIRCLE a hollow circle ARROW_FILLED_CIRCLE a filled circle ARROW_ARROW an arrow ARROW_SINGLE_OBLIQUE a single oblique ARROW_DOUBLE_OBLIQUE a double oblique ARROW_METAFILE custom, define in metafile ======================================== ==================================

required
`end`

may be one of the following

======================================== ================================== Arrow head type Description ======================================== ================================== ARROW_POSITION_END arrow appears at the end ARROW_POSITION_START arrow appears at the start ======================================== ==================================

required
`size`

specifies the lenght of the arrow

required
`xOffset`

specifies the offset from the end of the line

required
`name`

specifies a name

required
`mf`

mf can be a wxPseduoMetaFile, perhaps loaded from a simple Windows metafile.

required
`arrowId`

the id for the arrow

required

ClearArrowsAtPosition(end)

Delete the arrows at the specified position, or at any position if position is -1.

Parameters:

Name Type Description Default
`end`

position to clear arrow from

required

DeleteArrowHead(position, name)

Delete an arrowhead by position and name (position -1 matches any).

AddText(string, position=0)

Add a label line to a line region.

position is 0 for the middle of the line (the default), 1 for near the start and 2 for near the end.

SetLabelText(position, text)

Replace the label text of one line region.

GetLabelPosition(position)

Return the label anchor in diagram coordinates.

SetLabelPosition(position, x, y)

Offset a label from its default point on the line.

SetRouteMode(mode)

Set how the edge is drawn: "straight", "avoid" or "curved".

straight collapses back to an attached two-point line (any manual bend is dropped); avoid bends only when a box is in the way; curved always bows into a spline.

GetRouteMode()

Return the current routing mode (see :meth:SetRouteMode).

SetRouter(router)

Set a custom edge router (experimental API).

None clears the override so the canvas default applies. Setting a router enables routing when autoRoute is off.

GetRouter()

Return the edge's own router override (experimental API).

GetEffectiveRouter()

Resolve the router: edge override, canvas default, built-in.

Part of the experimental router-injection API.

RefreshEnds()

Re-clip both endpoints to their shapes without routing.

Useful after a batch move or layout for straight/manual edges, whose routing mode does not run the obstacle router.

UpdateRoute()

Route the line around foreign rectangles when autoRoute is on.

Returns the routing style (straight, curved or orthogonal), or None when routing does not apply. Endpoint clipping is recomputed from a straight line first, so a previous curve cannot feed back into the next route.

ResetRoute()

Collapse the edge to a straight, attached two-point line.

SetSpline(spline)

Draw a spline through the control points when True.

IsSpline()

Return True when the line is drawn as a spline.

Straighten(dc=None)

Straighten vertical and horizontal segments of the line.

MakeLineControlPoints(n)

Make a given number of control points.

Parameters:

Name Type Description Default
`n` int

number of control points, minimum of two

required

SetEnds(x1, y1, x2, y2)

Set the end positions of the line.

GetEnds()

Get the visible endpoints of the lines for drawing between two objects.

Routing modes accepted by SetRouteMode:

Mode Behaviour
"straight" always a straight line
"auto" straight when clear, a curve around boxes; never orthogonal
"avoid" straight, curve, then an orthogonal L/Z fallback
"curved" always a free curve
"orthogonal" always a stub + L/Z orthogonal route

ConnectionShape

The transient line drawn while dragging from an output port to an input port.

wxdiagram.ConnectionShape

Bases: LineShapeBase, Resizeable, Selectable

setInput(shape, portnum)

Set the object and port you are dragging/connecting from Assign to self.input which is a tuple comprising (shape, portnum) where the portnum is a rhs output portnum, since we draw from an output port to an input port.

Args: shape: the shape you are dragging from portnum: the port number 0..n you are dragging from

Returns: -

GetParent()

Get the parent of this shape, if it is part of a composite.

Arrow constants

Constant Meaning
ARROW_ARROW solid triangle
ARROW_DOUBLE_OBLIQUE open double line
ARROW_SINGLE_OBLIQUE open single line
ARROW_FILLED_CIRCLE filled circle
ARROW_HOLLOW_CIRCLE hollow circle
ARROW_POSITION_START / MIDDLE / END where on the line the head sits

Mixins

wxdiagram.Selectable

Allows Shape to be selected

Selected()

True if the shape is currently selected.

Select(select, dc=None)

Select or deselect the given shape, drawing or erasing control points (handles) as necessary.

Parameters:

Name Type Description Default
`select`

True to select

required
`dc`

the device context

required

wxdiagram.Resizeable

Creates resize Nodes that can be drug around the canvas to alter the shape or size of the Shape

wxdiagram.Connectable

Creates connection nodes or ports New version only has one port for in and one for out - at centre of shape's side And for drawing, the ConnectionShape asks the Shape for its centre via this class (Blocks etc. inherit from this class, thus have the getCentre() method available) Note, ConnectionShape does not inherit from this class.

connection_points()

Return the four side connection points, clipped to the perimeter.

The keys are left, right, top and bottom. Polygons use the intersection with their real edges, so a triangle's dots sit on the sloping sides rather than at the corners of its bounding box.

getPort(type, num)

Return a port position as (x, y).

Port 0 (the default) is the centre of the left side for inputs and the right side for outputs. Ports 1 and 2 are the centres of the top and bottom edges. The point is clipped to the shape's real perimeter, so polygons and ellipses get a port that is actually on their outline.

getCentre()

Return the centre of the shape's bounding box.

wxdiagram.Attributable

Allows AttributeEditor to edit specified properties of the Shape

Routing

route_edge is the pure routing function used by LineShape; it has no wx dependency, so it can be reused by a layout or a custom edge.

wxdiagram.routing.route_edge(p1, p2, obstacles, padding=ROUTE_PADDING, bend=ROUTE_BEND, spread=0.0, prefer_curve=False, prefer_orthogonal=False, allow_orthogonal=False, start_normal=None, end_normal=None)

Route an edge from p1 to p2 avoiding obstacles.

Returns (points, style) where style is straight, curved or orthogonal. Falls back to the straight segment if nothing clears.

prefer_curve asks for a free bezier even when the straight segment is clear (the usual look for UML class edges); prefer_orthogonal skips the straight/curve tiers and goes straight to an orthogonal L/Z route. Otherwise a clear segment stays straight and curves are only used to dodge boxes.

Orthogonal routing is used when prefer_orthogonal is set (force the L/Z route) or as a last resort when allow_orthogonal is set ("avoid" mode). The "auto" mode (straight or curved) never produces right-angle detours.

spread shifts the route sideways (perpendicular to the edge) so parallel edges between the same pair of shapes do not overlap. For a straight edge both endpoints move (along the shape sides); for the other styles only the interior points move, keeping the perimeter attachment exact.

start_normal / end_normal are the outward side normals at the two endpoints (used by the orthogonal fallback so the edge leaves perpendicular to the shape side instead of running along it).

Routers are injectable, but this layer is experimental and may change or be removed in a minor release. The stable surface is route_edge, LineShape.SetRouteMode and ShapeCanvas.RouteEdges.

To try the experimental API: implement BaseRouter.route() (and optionally route_many() for batch routing), register it with register_router, then attach it per edge (LineShape.SetRouter) or canvas-wide (ShapeCanvas.SetDefaultRouter). DefaultRouter wraps route_edge.

wxdiagram.routing.BaseRouter

Interface for injectable edge routers (experimental API).

route(request)

Route one edge; return None to leave the edge untouched.

route_many(requests)

Batch hook; the default loops over :meth:route.

wxdiagram.routing.DefaultRouter

Bases: BaseRouter

The built-in straight/curved/orthogonal router (experimental wrapper).

Layout

Layouts are pluggable and pure Python. Diagram.ApplyLayout collects top-level nodes and attached edges, runs the engine, and moves shapes to the resulting top-left positions; ShapeCanvas.ApplyLayout additionally re-routes edges, updates the scroll extent and refreshes the view.

result = canvas.ApplyLayout("spring", options={"spacing": 40, "seed": 1})
result.positions      # {node_id: (left, top)}
result.metadata       # crossings, edge lengths, refinement moves

SpringLayout options: spacing, seed, iterations, keep_positions, reduce_crossings and crossing_passes. A layout engine is any object with a name and a layout(nodes, edges, *, options=None, on_step=None) method; register it by name or pass the instance to ApplyLayout. See the layout tutorial for complete examples.

wxdiagram.SpringLayout

Fruchterman-Reingold style spring layout.

Options: spacing, seed, iterations, keep_positions, reduce_crossings (default True) and crossing_passes. metadata reports crossings and edge lengths before/after refinement.

wxdiagram.layout.LayoutNode dataclass

One box to place; x/y are the current top-left position.

wxdiagram.layout.LayoutEdge dataclass

One connection between two node ids.

wxdiagram.layout.LayoutResult dataclass

Engine outcome: top-left positions keyed by node id.

metadata is engine-specific; the bundled spring engine reports crossings, crossings_before, refinement_moves, edge_length and edge_length_before.

wxdiagram.get_layout(name_or_engine)

Resolve a layout engine from an instance, class or registered name.

wxdiagram.register_layout(name_or_engine, engine=None)

Register a layout engine instance (or class).

Usage::

register_layout("spring", SpringLayout())
register_layout(SpringLayout)  # uses ``SpringLayout.name``

wxdiagram.available_layouts()

Sorted list of registered layout names.

wxdiagram.collect_graph(diagram)

Collect (nodes, edges) from a diagram in one call.

wxdiagram.layout.nodes_from_diagram(diagram)

Collect layout nodes from top-level non-edge shapes.

Returns (nodes, id_by_shape) where id_by_shape maps id(shape) to the layout node id, for edge resolution.

wxdiagram.layout.edges_from_diagram(diagram, id_by_shape)

Collect layout edges from attached LineShape objects.

Crossing quality can be measured and refined independently:

wxdiagram.count_crossings(positions, edges)

Count proper crossings between non-incident edge pairs.

wxdiagram.total_edge_length(positions, edges)

Sum of straight centre-to-centre lengths, ignoring missing nodes.

wxdiagram.segments_cross(p1, p2, p3, p4)

True only for a proper crossing; touching/collinear is not counted.

wxdiagram.reduce_crossings(nodes, edges, positions, *, spacing=40.0, passes=4, step=None, min_step=None)

Move non-fixed nodes to reduce crossings, then return the new layout.

spacing controls the clearance kept between boxes and the default search step. The search is deterministic: nodes are visited in sorted-id order and candidates in a fixed direction order.

See also Layout and routing for the full options, custom engine and custom-router examples, and the appendix on the pynsource heritage.

Persistence

wxdiagram.persistence.save(diagram, path)

wxdiagram.persistence.load(path)