canvas(n)

โœจ NAME โœจ

okay so this is canvas from Tk Built-In Commands โ€” the manual name is canvas(n), and it's literally all about how to create and manipulate 'canvas' hypergraphics drawing surface widgets. ๐Ÿ’…


๐ŸŽ€ SYNOPSIS ๐ŸŽ€

canvas pathName ?options?

๐Ÿ’… STANDARD OPTIONS ๐Ÿ’…

here's the standard-options squad, bestie โ€” no cap, these are the vibes:

  • -background
  • -borderwidth
  • -cursor
  • -highlightbackground
  • -highlightcolor
  • -highlightthickness
  • -insertbackground
  • -insertborderwidth
  • -insertofftime
  • -insertontime
  • -insertwidth
  • -relief
  • -selectbackground
  • -selectborderwidth
  • -selectforeground
  • -takefocus
  • -xscrollcommand
  • -yscrollcommand

See the options manual entry for details on the standard options. โœจ


๐ŸŒธ WIDGET-SPECIFIC OPTIONS ๐ŸŒธ

  • -closeenough โ€” Database Name: closeEnough; Database Class: CloseEnough. This one takes a floating-point value that says how close the mouse cursor has to be to an item before it counts as being โ€œinsideโ€ that item. Defaults to 1.0.
  • -confine โ€” Database Name: confine; Database Class: Confine. A boolean value that says whether it's allowable to set the canvas's view outside the region defined by the scrollRegion argument. Defaults to true, which means the view gets constrained inside the scroll region.
  • -height โ€” Database Name: height; Database Class: Height. The desired window height that the canvas widget should request from its geometry manager. The value can be in any of the forms described in the COORDINATES section below.
  • -scrollregion โ€” Database Name: scrollRegion; Database Class: ScrollRegion. A list with four coordinates describing the left, top, right, and bottom coordinates of a rectangular region. This region is used for scrolling purposes and is considered the boundary of the information in the canvas. Each coordinate may be specified in any of the forms given in the COORDINATES section below.
  • -state โ€” Database Name: state; Database Class: State. Modifies the default state of the canvas, where state may be set to one of: normal, disabled, or hidden. Individual canvas objects all have their own state option which may override the default state. Many options can take separate specifications such that the appearance of the item can be different in different situations. The options that start with active control the appearance when the mouse pointer is over it, while the option starting with disabled controls the appearance when the state is disabled. Canvas items which are disabled will not react to canvas bindings.
  • -width โ€” Database Name: width; Database Class: width. The desired window width that the canvas widget should request from its geometry manager. The value can be in any of the forms described in the COORDINATES section below.
  • -xscrollincrement โ€” Database Name: xScrollIncrement; Database Class: ScrollIncrement. Specifies an increment for horizontal scrolling, in any of the usual forms permitted for screen distances. If the value of this option is greater than zero, the horizontal view in the window will be constrained so that the canvas x coordinate at the left edge of the window is always an even multiple of xScrollIncrement; furthermore, the units for scrolling (e.g., the change in view when the left and right arrows of a scrollbar are selected) will also be xScrollIncrement. If the value of this option is negative or zero, then horizontal scrolling is unconstrained.
  • -yscrollincrement โ€” Database Name: yScrollIncrement; Database Class: ScrollIncrement. Specifies an increment for vertical scrolling, in any of the usual forms permitted for screen distances. If the value of this option is greater than zero, the vertical view in the window will be constrained so that the canvas y coordinate at the top edge of the window is always an even multiple of yScrollIncrement; furthermore, the units for scrolling (e.g., the change in view when the top and bottom arrows of a scrollbar are selected) will also be yScrollIncrement. If the value of this option is negative or zero, then vertical scrolling is unconstrained.

๐Ÿฆ‹ INTRODUCTION ๐Ÿฆ‹

okay so the canvas command creates a new window โ€” that's the pathName argument โ€” and makes it into a canvas widget. โœจ Additional options, the ones up above, may be specified on the command line or in the option database to configure aspects of the canvas such as its colors and 3-D relief. The canvas command returns its pathName argument. At the time this command is invoked, there must not exist a window named pathName, but pathName's parent must exist. ๐Ÿ’–

Canvas widgets implement structured graphics. A canvas displays any number of items, which may be things like rectangles, circles, lines, and text. Items may be manipulated (e.g. moved or re-colored) and commands may be associated with items in much the same way that the bind command allows commands to be bound to widgets. For example, a particular command may be associated with the <Button-1> event so that the command is invoked whenever button 1 is pressed with the mouse cursor over an item. This means that items in a canvas can have behaviors defined by the Tcl scripts bound to them. ๐Ÿ”ฅ


๐ŸŒˆ DISPLAY LIST ๐ŸŒˆ

The items in a canvas are ordered for purposes of display, with the first item in the display list being displayed first, followed by the next item in the list, and so on. Items later in the display list obscure those that are earlier in the display list and are sometimes referred to as being โ€œon topโ€ of earlier items. When a new item is created it is placed at the end of the display list, on top of everything else. Widget commands may be used to re-arrange the order of the display list.

Window items are an exception to the above rules. The underlying window systems require them always to be drawn on top of other items. In addition, the stacking order of window items is not affected by any of the canvas widget commands; you must use the Tk raise command and lower command instead.


๐Ÿ‘‘ ITEM IDS AND TAGS ๐Ÿ‘‘

Items in a canvas widget may be named in either of two ways: by id or by tag. Each item has a unique identifying number, which is assigned to that item when it is created. The id of an item never changes and id numbers are never re-used within the lifetime of a canvas widget.

Each item may also have any number of tags associated with it. A tag is just a string of characters, and it may take any form except that of an integer. For example, โ€œx123โ€ is OK but โ€œ123โ€ is not. The same tag may be associated with many different items. This is commonly done to group items in various interesting ways; for example, all selected items might be given the tag โ€œselectedโ€.

The tag all is implicitly associated with every item in the canvas; it may be used to invoke operations on all the items in the canvas.

The tag current is managed automatically by Tk; it applies to the current item, which is the topmost item whose drawn area covers the position of the mouse cursor (different item types interpret this in varying ways; see the individual item type documentation for details). If the mouse is not in the canvas widget or is not over an item, then no item has the current tag.

When specifying items in canvas widget commands, if the specifier is an integer then it is assumed to refer to the single item with that id. If the specifier is not an integer, then it is assumed to refer to all of the items in the canvas that have a tag matching the specifier. The symbol tagOrId is used below to indicate that an argument specifies either an id that selects a single item or a tag that selects zero or more items.

tagOrId may contain a logical expressions of tags by using operators: โ€œ&&โ€, โ€œ||โ€, โ€œ^โ€, โ€œ!โ€, and parenthesized subexpressions. For example:

.c find withtag {(a&&!b)||(!a&&b)}

or equivalently:

.c find withtag {a^b}

will find only those items with either โ€œaโ€ or โ€œbโ€ tags, but not both.

Some widget commands only operate on a single item at a time; if tagOrId is specified in a way that names multiple items, then the normal behavior is for the command to use the first (lowest) of these items in the display list that is suitable for the command. Exceptions are noted in the widget command descriptions below.

๐ŸŒธ COORDINATES ๐ŸŒธ

okay so bestie, every single coordinate that has anything to do with canvases is stored as a floating-point number. that's the whole vibe. ๐Ÿ’…

Coordinates and distances get specified in screen units, which are floating-point numbers optionally followed by one of several letters:

  • no letter at all โ†’ the distance is in pixels (the default, the moment, the standard)
  • m โ†’ millimeters on the screen
  • c โ†’ centimeters
  • i โ†’ inches
  • p โ†’ printers points (that's 1/72 inch, no cap)

And the axes, bestie: larger y-coordinates point lower on the screen, and larger x-coordinates point farther to the right. yes, y goes down, it's giving math-class betrayal but that's just how it is. ๐Ÿ˜ญ

You can hand over coordinates either as an even number of parameters, or as a single list parameter containing an even number of x and y values. Even. Always even. ๐ŸŒˆ


๐Ÿฆ‹ TRANSFORMATIONS ๐Ÿฆ‹

Normally the origin of the canvas coordinate system sits at the upper-left corner of the window that contains the canvas. Iconic placement honestly.

But plot twist: you can adjust the origin of the canvas coordinate system relative to the window's origin using the xview and yview widget commands. That's typically the scrolling move, iykyk.

๐Ÿšจ but listen: canvases do NOT support scaling or rotation of the canvas coordinate system relative to the window coordinate system. that is simply not a thing this widget does. periodt.

Individual items can be moved, scaled or rotated using widget commands described below though โ€” so it's not all hopeless. ๐Ÿซถ

Also, super important note: the default origin of the canvas's visible area is coincident with the origin for the whole window, because that makes bindings using the mouse position way easier to work with. you only need the canvasx and canvasy widget commands if you actually go and adjust the origin of the visible area. โœจ

But (and this is the catch ๐Ÿ’€) that also means that any focus ring โ€” as controlled by the -highlightthickness option โ€” and the window border โ€” as controlled by the -borderwidth option โ€” must be taken into account before you get to the visible area of the canvas. count the pixels, bestie. ๐ŸŽ€


๐Ÿ’– INDICES ๐Ÿ’–

Text items support the whole notion of an index for identifying particular positions within the item. and in a similar fashion, line and polygon items support indices for identifying, inserting and deleting subsets of their coordinates. ๐ŸŒธ

Indices are what you use for commands like inserting or deleting a range of characters or coordinates, and for setting the insertion cursor position.

An index may be specified in any of a number of ways, and different types of items may support different forms for specifying indices. Text items support the following forms โ€” and if you go define new types of text-like items, it would be advisable to support as many of these forms as practical. (do it for the culture ๐Ÿซถ)

โญ note that it is possible to refer to the character just after the last one in the text item. this is necessary for tasks like inserting new text at the end of the item. the afterparty character, if you will.
๐Ÿ”ฅ and Lines and Polygons do not support the insertion cursor and the selection. their indices are supposed to be even always, because coordinates always appear in pairs. even. always. periodt.
  • number โ€” A decimal number giving the position of the desired character within the text item. 0 refers to the first character, 1 to the next character, and so on. If indexes are odd for lines and polygons, they will be automatically decremented by one. A negative number is treated as if it were zero, and a number greater than the length of the text item is treated as if it were equal to the length of the text item. For polygons, negative numbers or numbers greater than the length of the coordinate list will be adjusted by adding or subtracting the length until the result is between zero and the length, inclusive. โœจ
  • end โ€” Refers to the character or coordinate just after the last one in the item (same as the number of characters or coordinates in the item).
  • insert โ€” Refers to the character just before which the insertion cursor is drawn in this item. Not valid for lines and polygons.
  • sel.first โ€” Refers to the first selected character in the item. If the selection is not in this item then this form is illegal. ๐Ÿ˜ญ
  • sel.last โ€” Refers to the last selected character in the item. If the selection is not in this item then this form is illegal. ๐Ÿ˜ญ
  • @x,y โ€” Refers to the character or coordinate at the point given by x and y, where x and y are specified in the coordinate system of the canvas. If x and y lie outside the coordinates covered by the text item, then they refer to the first or last character in the line that is closest to the given point. ๐Ÿ’…

๐ŸŽ€ DASH PATTERNS ๐ŸŽ€

Many items support the notion of a dash pattern for outlines. let's get into it.

The first possible syntax is a list of integers. Each element represents the number of pixels of a line segment. Only the odd segments are drawn using the โ€œoutlineโ€ color. The other segments are drawn transparent. ๐ŸŒˆ

The second possible syntax is a character list containing only 5 possible characters: โ€œ.,-_ โ€ โ€” yes, that space is one of the characters, bestie. The space can be used to enlarge the space between other line elements, and it cannot occur as the first position in the string.

Some examples, and these are exact, do not touch:

-dash .     โ†’ -dash {2 4}
-dash -     โ†’ -dash {6 4}
-dash -.    โ†’ -dash {6 4 2 4}
-dash -..   โ†’ -dash {6 4 2 4 2 4}
-dash {. }  โ†’ -dash {2 8}
-dash ,     โ†’ -dash {4 4}

The main difference of this syntax from the previous one is that it is shape-conserving. ๐Ÿซถ This means that all values in the dash list will be multiplied by the line width before display. This assures that โ€œ.โ€ will always be displayed as a dot and โ€œ-โ€ always as a dash, regardless of the line width. it's giving consistency. it's giving โœจ.

On systems which support only a limited set of dash patterns, the dash pattern will be displayed as the closest dash pattern that is available. For example, on Windows only the first 4 of the above examples are available. The last 2 examples will be displayed identically to the first one. ๐Ÿ’€ (not the Windows L, sorry not sorry)


๐Ÿ‘‘ WIDGET COMMAND ๐Ÿ‘‘

The canvas command creates a new Tcl command whose name is pathName. This command may be used to invoke various operations on the widget. It has the following general form:

pathName option ?arg ...?

Option and the args determine the exact behavior of the command. The following widget commands are possible for canvas widgets:


๐Ÿ’œ pathName addtag tag searchSpec ?arg ...?

For each item that meets the constraints specified by searchSpec and the args, add tag to the list of tags associated with the item if it is not already present on that list. It is possible that no items will satisfy the constraints given by searchSpec and args, in which case the command has no effect. This command returns an empty string as result.

SearchSpec and arg's may take any of the following forms:

  • above tagOrId โ€” Selects the item just after (above) the one given by tagOrId in the display list. If tagOrId denotes more than one item, then the last (topmost) of these items in the display list is used.
  • all โ€” Selects all the items in the canvas. every single one. the whole squad. ๐Ÿ’…
  • below tagOrId โ€” Selects the item just before (below) the one given by tagOrId in the display list. If tagOrId denotes more than one item, then the first (lowest) of these items in the display list is used.
  • closest x y ?halo? ?start? โ€” Selects the item closest to the point given by x and y. If more than one item is at the same closest distance (e.g. two items overlap the point), then the top-most of these items (the last one in the display list) is used. If halo is specified, then it must be a non-negative value. Any item closer than halo to the point is considered to overlap it. The start argument may be used to step circularly through all the closest items. If start is specified, it names an item using a tag or id (if by tag, it selects the first item in the display list with the given tag). Instead of selecting the topmost closest item, this form will select the topmost closest item that is below start in the display list; if no such item exists, then the selection behaves as if the start argument had not been specified. ๐Ÿ”ฅ
  • enclosed x1 y1 x2 y2 โ€” Selects all the items completely enclosed within the rectangular region given by x1, y1, x2, and y2. X1 must be no greater than x2 and y1 must be no greater than y2. (order matters bestie ๐Ÿซถ)
  • overlapping x1 y1 x2 y2 โ€” Selects all the items that overlap or are enclosed within the rectangular region given by x1, y1, x2, and y2. X1 must be no greater than x2 and y1 must be no greater than y2.
  • withtag tagOrId โ€” Selects all the items given by tagOrId. straightforward. iconic. no notes. โœจ

๐Ÿงš pathName bbox tagOrId ?tagOrId tagOrId ...?

Returns a list with four elements giving an approximate bounding box for all the items named by the tagOrId arguments.

The list has the form โ€œx1 y1 x2 y2โ€ such that the drawn areas of all the named elements are within the region bounded by x1 on the left, x2 on the right, y1 on the top, and y2 on the bottom.

โš ๏ธ the return value may overestimate the actual bounding box by a few pixels. it's approximate, bestie, it's doing its best. ๐Ÿ˜ญ

If no items match any of the tagOrId arguments, or if the matching items have empty bounding boxes (i.e. they have nothing to display) then an empty string is returned. ๐Ÿ’€

pathName bind tagOrId ?sequence? ?command? ๐Ÿ’…

Okay so this is basically the bind command but make it item-flavored ๐Ÿ“. It glues command onto every single item you name with tagOrId, so that whenever the event sequence happens for one of those items, boom โ€” your command runs. Same energy as regular bind, except it lives on items inside a canvas instead of whole widgets. For the full tea on how sequence is written and what substitutions get done to command before it fires, go read the bind manual entry. It's all there, bestie, I'm not retyping it ๐Ÿซถ.

  • If you give it all the arguments, a brand new binding is created, and it replaces any existing binding for that same sequence and tagOrId. Unless โ€” plot twist โ€” the first character of command is "+", in which case command augments the existing binding instead of yeeting it. Either way, the return value is an empty string.
  • If command is omitted, you get back the command associated with tagOrId and sequence. And if there's no such binding? Error. ๐Ÿ˜ญ
  • If both command and sequence are omitted, you get a list of every sequence that has bindings defined for tagOrId.

The only events you can bind to are mouse and keyboard ones (like Enter, Leave, Button, Motion, and Key) or virtual events. Canvas event handling rides on the current item from ITEM IDS AND TAGS up above ๐Ÿ‘†. Enter and Leave fire for an item when it becomes the current item or stops being the current item โ€” and heads up, these are not the same as Enter and Leave events for windows, okay? Different vibe entirely. Mouse-related events go to the current item, if there is one. Keyboard-related events go to the focus item, if there is one (peep the focus widget command below for more on that). And if a virtual event shows up in a binding, that binding can only trigger if the virtual event is defined by an underlying mouse-related or keyboard-related event. No defining it out of thin air, sorry babe ๐Ÿ’€.

Now, multiple bindings can match one event. Like, say one binding is tied to the item's id and another is tied to one of the item's tags. When that happens, all of the matching bindings get invoked โœจ. The order is sacred:

  1. A binding associated with the all tag runs first ๐Ÿ‘‘
  2. Then one binding for each of the item's tags, in order
  3. Then a binding associated with the item's id

And if there are multiple matching bindings for a single tag, only the most specific one gets invoked. A continue command inside a binding script terminates that script; a break command terminates that script and skips any remaining scripts for the event โ€” exactly like with the bind command, no cap.

One more thing ๐ŸŽ€: if bindings were created for a canvas window using the bind command, they get invoked in addition to the bindings created for the canvas's items via this bind widget command. And the item bindings go first, before any of the bindings for the window as a whole. Items stay winning ๐Ÿ’œ.


pathName canvasx screenx ?gridspacing?

You hand it a window x-coordinate in the canvas, screenx, and it hands you back the canvas x-coordinate that's being displayed at that exact spot. If you toss in gridspacing, the canvas coordinate gets rounded to the nearest multiple of gridspacing units. Snappy ๐Ÿ“.

pathName canvasy screeny ?gridspacing?

Same deal but the y-axis, bestie. Give it a window y-coordinate in the canvas, screeny, and it returns the canvas y-coordinate displayed there. With gridspacing, the canvas coordinate rounds to the nearest multiple of gridspacing units. โœจ

pathName cget option

Returns the current value of whatever configuration option you ask for. And option can be any of the values the canvas command accepts. Go wild ๐Ÿ’….

pathName configure ?option? ?value? ?option value ...?

Query or modify the widget's config options, queen ๐Ÿ‘‘.

  • No option at all? You get a list describing every available option for pathName (check Tk_ConfigureInfo for what that list looks like).
  • option but no value? You get a list describing just that one named option โ€” identical to the matching sublist of the big list you'd get with no arguments.
  • One or more option-value pairs? The command modifies the given widget option(s) to hold the given value(s), and returns an empty string.

And option may have any of the values accepted by the canvas command, fr fr.

pathName coords tagOrId ?x0 y0 ...?

pathName coords tagOrId ?coordList?

Query or modify the coordinates that define an item ๐Ÿ“.

  • No coordinates given โ†’ returns a list whose elements are the coordinates of the item named by tagOrId.
  • Coordinates given โ†’ they replace the current coordinates for the named item.
  • If tagOrId points at multiple items, only the first one in the display list gets used.
Heads up though ๐Ÿšจ: for rectangles, ovals and arcs, the returned list of coordinates has a fixed order โ€” left, top, right and bottom โ€” which might not be the order you originally gave. Also, coordinates are always returned in screen units with no units (that is, in pixels). So if you originally specified them in centimeters or inches, guess what, you're getting pixels back anyway. The math said so ๐Ÿ’….

pathName create type x y ?x y ...? ?option value ...?

pathName create type coordList ?option value ...?

Makes a brand new item in pathName of type type ๐ŸŒฑ. What exactly comes after type depends on type, but usually it's the coordinates for one or more points, then specs for zero or more item options. Peep the subsections on the individual item types below for the full syntax tea. This command returns the id for the new item โ€” remember it, you'll need it ๐Ÿ”ฅ.

pathName dchars tagOrId first ?last?

For every item given by tagOrId, delete the characters โ€” or coordinates โ€” in the range from first to last, inclusive โœ‚๏ธ. If some of the items given by tagOrId don't support indexing operations, they just ignore this whole thing. Text items read first and last as indices to a character; line and polygon items read them as indices to a coordinate (an x,y pair). Indices are described in INDICES above, bestie. If last is omitted, it defaults to first. Returns an empty string.

pathName delete ?tagOrId tagOrId ...?

Deletes each of the items given by each tagOrId, and returns an empty string. Poof, gone ๐Ÿฆ‹.

pathName dtag tagOrId ?tagToDelete?

For each of the items given by tagOrId, delete the tag tagToDelete from the list of tags associated with that item ๐Ÿท๏ธ. If an item doesn't have the tag tagToDelete, it's completely unaffected โ€” no drama, no error. If tagToDelete is omitted, it defaults to tagOrId. Returns an empty string.

pathName find searchCommand ?arg ...?

Returns a list of all the items that meet the constraints you set with searchCommand and arg's ๐Ÿ”. SearchCommand and the args can take any of the forms the addtag command accepts. Items come back in stacking order, with the lowest item first. Respect the stack ๐Ÿ’œ.

pathName focus ?tagOrId?

Sets the keyboard focus for the canvas widget to the item given by tagOrId โŒจ๏ธโœจ.

  • If tagOrId refers to several items, focus goes to the first such item in the display list that supports the insertion cursor.
  • If tagOrId refers to no items, or none of them support the insertion cursor, then the focus is not changed. Sorry ๐Ÿซ .
  • If tagOrId is an empty string, the focus item resets so that no item has the focus.
  • If tagOrId isn't specified at all, the command returns the id for the item that currently has the focus โ€” or an empty string if no item has it.

Once focus is set to an item, that item displays the insertion cursor and all keyboard events get directed to it ๐ŸŽฏ. But listen: the focus item within a canvas and the focus window on the screen (set with the focus command) are totally independent. An item doesn't actually have the input focus unless (a) its canvas is the focus window and (b) the item is the focus item within the canvas. In most cases it's advisable to follow the focus widget command with the focus command to set the focus window to the canvas โ€” if it wasn't there already. Double-check your vibes, bestie ๐Ÿ’….

pathName gettags tagOrId

Returns a list whose elements are the tags associated with the item given by tagOrId ๐Ÿท๏ธ. If tagOrId refers to more than one item, the tags come from the first such item in the display list. If tagOrId refers to no items, or the item has no tags at all, then you get an empty string back. Simple as ๐ŸŒธ.

pathName icursor tagOrId index

Sets the position of the insertion cursor for the item(s) given by tagOrId to just before the character whose position is given by index โœ๏ธ. If some or all of the items given by tagOrId don't support an insertion cursor, this command has no effect on them โ€” no harm done. See INDICES above for a description of the legal forms for index.

Note that the insertion cursor is only displayed in an item if that item currently has the keyboard focus (see the focus widget command, above) โ€” but the cursor position can still be set even when the item doesn't have the focus. Sneaky but legal ๐Ÿ˜Œ.

Returns an empty string.

pathName image imagename ?subsample? ?zoom?

Draws the canvas into the Tk photo image named imagename ๐Ÿ–ผ๏ธโœจ.

  • If a -scrollregion has been defined, then that's the boundaries of the canvas region drawn, and also the final size of the photo image.
  • Otherwise, the widget width and height with an origin of 0,0 is the size of the canvas region drawn and the final size of the photo image.

Optionally you can pass an integer subsample factor, and the photo image gets reduced in size. Tiny canvas, big energy ๐Ÿงš.

Also? You can hand it an integer zoom factor on top of the subsample, and the photo image gets enlarged. The empty space around it gets filled with the canvas background colour. And here's the tea: the canvas widget doesn't even need to be mapped for this widget command to work โ€” but at least one of its ancestors must be mapped. So like, somebody up the family tree has to be on screen.

This command returns an empty string. ๐Ÿ’ซ


  • pathName imove tagOrId index x y โ€” takes the index'th coordinate of every item that tagOrId points at and relocates it to the location (x,y). Each item reads index all on its own, following the rules from INDICES above. And out of the standard item set? Only line and polygon items are allowed to have their coordinates moved around like this. The rest said no. ๐Ÿ’…
  • pathName index tagOrId index โ€” hands you back a decimal string with the numerical index inside tagOrId that matches index. That index is a textual description of the position you want, exactly like INDICES above lays out. Text items read index as an index to a character; line and polygon items read it as an index to a coordinate (that's an x,y pair, bestie). The return value is guaranteed to sit between 0 and the number of characters, or coordinates, inside the item โ€” inclusive. And if tagOrId is referring to multiple items? Then the index gets processed in the first of those items that actually supports indexing operations, in display list order. First come, first served. ๐ŸŽ€
  • pathName insert tagOrId beforeThis string โ€” for every item given by tagOrId, if that item supports text or coordinate, then string gets inserted into the item's text right before the character โ€” or coordinate โ€” whose index is beforeThis. Text items read beforeThis as an index to a character; line and polygon items read it as an index to a coordinate (x,y pair, you know the vibe). For lines and polygons the string has to be a valid coordinate sequence. No fake coordinates allowed, periodt.

Peep INDICES above for the forms that are allowed for beforeThis.

This command returns an empty string. โœจ

  • pathName itemcget tagOrId option โ€” returns the current value of the configuration option, for the item given by tagOrId, whose name is option. It's basically the cget widget command's twin, except it applies to one particular item instead of the whole widget. option can be any of the values the create widget command accepted back when the item was created. And if tagOrId is a tag that points at more than one item, the first (lowest) one gets used. Lowest wins, always. ๐Ÿซถ
  • pathName itemconfigure tagOrId ?option? ?value? ?option value ...? โ€” same energy as the configure widget command, but it tweaks item-specific options for the items given by tagOrId instead of messing with the whole canvas widget's options. Here's the breakdown:
    • no option at all โ†’ you get a list describing all the available options for the first item given by tagOrId (check Tk_ConfigureInfo for how that list is formatted).
    • option with no value โ†’ you get a list describing that one named option. This list will be identical to the corresponding sublist of the value you'd get if you specified no option.
    • one or more option-value pairs โ†’ the command modifies those widget options to have those values in each of the items given by tagOrId, and returns an empty string.

The options and values are the same ones that are permissible in the create widget command when the item(s) were created โ€” scroll down to the sections about individual item types for the details on what's legal. ๐Ÿ˜Œ

  • pathName lower tagOrId ?belowThis? โ€” moves all the items given by tagOrId to a new position in the display list, right before the item given by belowThis. If tagOrId refers to more than one item, they all get moved, but the relative order between the moved items doesn't change. belowThis is a tag or an id; if it refers to more than one item, the first (lowest) of those items in the display list becomes the destination spot for the moved items.
Heads up bestie: this command does nothing to window items. Window items always obscure every other item type, and the stacking order of window items is decided by the raise command and lower command โ€” not the raise widget command and lower widget command for canvases. Two different things, don't mix them up. ๐Ÿ˜ญ

This command returns an empty string.

  • pathName move tagOrId xAmount yAmount โ€” moves each item given by tagOrId in the canvas coordinate space by adding xAmount to the x-coordinate of every point tied to the item, and yAmount to the y-coordinate of every point tied to the item. Slides the whole thing, no cap. Returns an empty string. ๐Ÿฆ‹
  • pathName moveto tagOrId xPos yPos โ€” moves the items given by tagOrId in the canvas coordinate space so that the first coordinate pair (aka the upper-left corner of the bounding box) of the first item (the lowest in the display list) carrying the tag tagOrId lands at position (xPos,yPos). Fun fact: xPos and yPos can be the empty string, and then that coordinate just stays unchanged. Every item matching tagOrId keeps the same positions relative to each other. Returns an empty string. ๐Ÿ’–

โœจ postscript โœจ

  • pathName postscript ?option value option value ...? โ€” generates a Postscript representation of part or all of the canvas. Iconic, honestly.

Here's how it goes down:

  • If the -file option is given, the Postscript gets written to a file and an empty string comes back. Otherwise, the Postscript is returned as the result of the command. โœ๏ธ
  • If the interpreter that owns the canvas is marked as safe, the operation will fail, because safe interpreters are not allowed to write files. Sorry babe, rules are rules. ๐Ÿšซ
  • If the -channel option is given, the argument is the name of a channel that's already open for writing. The Postscript goes to that channel, and the channel is left open for further writing once the operation ends.
  • The Postscript is created in Encapsulated Postscript form using version 3.0 of the Document Structuring Conventions.
Note: by default, Postscript is only generated for information that appears in the canvas's window on screen. If the canvas was freshly created it might still have its initial size of 1x1 pixel, so literally nothing will show up in the Postscript. ๐Ÿ˜ญ To dodge that whole situation, either invoke the update command to wait for the canvas window to reach its final size, or use the -width and -height options to spell out the area of the canvas you want printed.

The option-value pairs give extra info to control how the Postscript gets generated. These are the supported options:

  • -channel channelName โ€” names the channel to write the Postscript to. If this option and the -file option are both absent, then the Postscript comes back as the result of the command. ๐ŸŒŠ
  • -colormap varName โ€” varName must be the name of an array variable that specifies a color mapping to use in the Postscript. Every element of varName must consist of Postscript code that sets a particular color value (e.g. 1.0 1.0 0.0 setrgbcolor). When outputting color info in the Postscript, Tk checks whether there's an element of varName with the same name as the color. If there is, Tk uses that element's value as the Postscript command to set the color. ๐ŸŽจ

If this option hasn't been specified, or if there's no entry in varName for a given color, then Tk uses the red, green, and blue intensities from the X color instead.

  • -colormode mode โ€” says how to output color information. mode must be one of:
    • color โ€” for full color output
    • gray โ€” converts all colors to their gray-scale equivalents
    • mono โ€” converts all colors to black or white

Pick your fighter. ๐ŸŒˆ

  • -file fileName โ€” names the file to write the Postscript into. If this option and the -channel option are both absent, then the Postscript comes back as the result of the command. ๐Ÿ“
  • -fontmap varName โ€” varName must be the name of an array variable that specifies a font mapping to use in the Postscript. Every element of varName must consist of a Tcl list with two elements: the name and the point size of a Postscript font. When outputting Postscript commands for a particular font, Tk checks whether varName contains an element with the same name as the font. If it does, that element's font info gets used in the Postscript. Otherwise Tk tries to guess what Postscript font to use. And ngl, Tk's guesses generally only work for well-known fonts like Times and Helvetica and Courier, and only if the X font name doesn't omit any dashes up through the point size. ๐Ÿ˜ฌ

For example, -*-Courier-Bold-R-Normal--*-120-* will work, but *Courier-Bold-R-Normal*120* will not โ€” Tk needs those dashes to parse the font name.

  • -height size โ€” the height of the area of the canvas to print. Defaults to the height of the canvas window. ๐Ÿ“
  • -pageanchor anchor โ€” says which point of the printed area of the canvas should sit over the positioning point on the page (that point is given by the -pagex and -pagey options). โœจ

For example, -pageanchor n means the top center of the area of the canvas being printed (as it shows up in the canvas window) should be over the positioning point. Defaults to center. ๐Ÿ’…

  • -pageheight size โ€” bestie, this makes the Postscript scale in both x and y so the printed area comes out size tall on the page. ๐Ÿซถ size is a floating-point number with a lil unit suffix: c for centimeters, i for inches, m for millimeters, or p (or nothing at all) for printer's points (that's 1/72 inch, iykyk). Defaults to the height of the printed area on the screen. And heads up: if you set both -pageheight and -pagewidth, the scale factor from -pagewidth is the one that's used (non-uniform scaling is not implemented, so no stretching shenanigans โœจ).
  • -pagewidth size โ€” same energy as -pageheight but for width: the Postscript scales in both x and y so the printed area is size wide on the page. size takes the exact same form as -pageheight. Defaults to the width of the printed area on the screen. If both -pageheight and -pagewidth are specified, the scale factor from -pagewidth is used (again, non-uniform scaling is not implemented ๐Ÿ’…).
  • -pagex position โ€” position is the x-coordinate of the positioning point on the Postscript page, and it accepts any of the forms allowed for -pageheight. You use it together with -pagey and -pageanchor to decide where the printed area actually lands on the Postscript page. Defaults to the center of the page. ๐ŸŽฏ
  • -pagey position โ€” the y-coordinate twin of -pagex: position is the y-coordinate of the positioning point on the Postscript page, same forms as -pageheight. Works with -pagex and -pageanchor to place the printed area. Defaults to the center of the page. ๐ŸŽฏ
  • -rotate boolean โ€” boolean says whether the printed area gets rotated 90 degrees. In non-rotated output the x-axis of the printed area runs along the short dimension of the page (that's "portrait" orientation, gorgeous); in rotated output the x-axis runs along the long dimension ("landscape" orientation, main character energy ๐ŸŒˆ). Defaults to non-rotated.
  • -width size โ€” sets the width of the area of the canvas you wanna print. Defaults to the width of the canvas window.
  • -x position โ€” the x-coordinate of the left edge of the area of the canvas being printed, in canvas coordinates, not window coordinates (important!! don't mix them up ๐Ÿ’€). Defaults to the coordinate of the left edge of the window.
  • -y position โ€” the y-coordinate of the top edge of the area of the canvas being printed, in canvas coordinates, not window coordinates. Defaults to the coordinate of the top edge of the window.

pathName raise tagOrId ?aboveThis?

Move all the items given by tagOrId to a new spot in the display list, right after the item given by aboveThis. ๐Ÿฆ‹ If tagOrId points at more than one item, they all get moved, but the relative order of the moved items stays exactly the same (no reshuffling, periodt). aboveThis is a tag or an id; if it refers to more than one item, then the last (topmost) of those items in the display list is the one used as the destination for the moved items. This command returns an empty string.

Lowkey important: this command has no effect on window items. Window items always obscure other item types, and the stacking order of window items is decided by the raise command and the lower command โ€” not by the raise widget command and the lower widget command for canvases. Don't @ me, that's just how it is. ๐Ÿ™ˆ

pathName rchars tagOrId first last string

This one swaps out the text or coordinates between first and last for each of the items indicated by tagOrId, replacing them with string. Each item reads first and last independently, following the rules in INDICES up above. ๐Ÿ“– Out of the standard item squad: text items support this by changing their text as directed, and line and polygon items support it by changing their coordinate list (and in that case string should be a list of coordinates to use as the replacement). The other items just ignore this operation entirely, not their problem. ๐Ÿ’…


pathName rotate tagOrId xOrigin yOrigin angle

Rotate the coordinates of all the items given by tagOrId, in canvas coordinate space. ๐Ÿ”„ xOrigin and yOrigin identify the origin for the rotation, and angle is how much to rotate the coordinates anticlockwise, in degrees (negative values rotate clockwise, so go off with the negative if that's your vibe). This command returns an empty string.

Implementation note, bestie, listen up: not all item types behave the same under rotations. Specifically, bitmap, image, text and window items only rotate their anchor points โ€” they do not rotate the items themselves about those points. And the arc, oval and rectangle types rotate about a computed center point instead of directly moving the bounding box coordinates. It's giving "it depends" ๐Ÿ˜ญ

Some items (currently arc and text) have angles in their own options; this command does not touch those options. Nope, they stay right where they are. โœ‹


pathName scale tagOrId xOrigin yOrigin xScale yScale

Rescale the coordinates of all the items given by tagOrId, in canvas coordinate space. ๐Ÿ“ xOrigin and yOrigin identify the origin for the scaling, and xScale and yScale are the scale factors for x- and y-coordinates respectively (a scale factor of 1.0 means no change to that coordinate โ€” leave it alone, she's fine). For each of the points defining each item, the x-coordinate gets adjusted so its distance from xOrigin changes by a factor of xScale. Same deal for y: each y-coordinate's distance from yOrigin changes by a factor of yScale. This command returns an empty string.

Heads up: some items only have a single pair of coordinates (looking at you, text, images and windows ๐Ÿ‘€), so scaling them with this command can only move them around โ€” there's nothing else to stretch.

pathName scan option args

This command is what makes scanning happen on canvases. It has two forms, depending on option:

pathName scan mark x y

Records x and y plus the canvas's current view. Used together with later scan dragto commands. Typically this is tied to a mouse button press in the widget, with x and y being the mouse coordinates. Returns an empty string. ๐Ÿ–ฑ๏ธ

pathName scan dragto x y ?gain?

This one computes the difference between its x and y arguments (usually mouse coordinates) and the x and y arguments from the last scan mark command for the widget. Then it adjusts the view by gain times that difference in coordinates, where gain defaults to 10. Usually tied to mouse motion events in the widget, so you get that "dragging the canvas at high speed through its window" effect. ๐ŸŽ๏ธ The return value is an empty string.


pathName select option ?tagOrId arg?

Manipulates the selection in one of several ways, depending on option. The command can take any of the forms described below. In all of these descriptions, tagOrId has to refer to an item that supports indexing and selection; if it refers to multiple items, then the first of those that supports indexing and selection is the one used. Index gives a textual description of a position within tagOrId, exactly as described in INDICES above. โœจ

pathName select adjust tagOrId index

Find the end of the selection in tagOrId nearest to the character given by index, then adjust that end of the selection to sit at index (i.e. it includes but does not go beyond index). The other end of the selection becomes the anchor point for future select to commands. If the selection isn't currently in tagOrId, this command behaves the same as the select to widget command. Returns an empty string.

pathName select clear

Clear the selection if it's in this widget. If the selection isn't in this widget, the command does nothing at all. Returns an empty string. ๐Ÿงน

pathName select from tagOrId index

Set the selection anchor point for the widget to be just before the character given by index in the item given by tagOrId. This command does not change the selection โ€” it just sets the fixed end of the selection for future select to commands. Returns an empty string. ๐Ÿ“Œ

pathName select item

Returns the id of the selected item, if the selection is in an item in this canvas. If the selection isn't in this canvas, you get an empty string back. ๐Ÿ’”

pathName select to tagOrId index

Set the selection to be those characters of tagOrId between the selection anchor point and index. The new selection will include the character given by index; it includes the character given by the anchor point only if index is greater than or equal to the anchor point. The anchor point is determined by the most recent select adjust or select from command for this widget. If the selection anchor point for the widget isn't currently in tagOrId, then it gets set to the same character given by index. Returns an empty string.


pathName type tagOrId

Returns the type of the item given by tagOrId, like rectangle or text. If tagOrId refers to more than one item, you get the type of the first item in the display list. If tagOrId doesn't refer to any items at all, then you get an empty string. ๐Ÿท๏ธ


pathName xview ?args?

This command queries and changes the horizontal position of the information displayed in the canvas's window. It can take any of the following forms: ๐Ÿ‘‘

...

pathName xview โ€” the forms, one by one ๐Ÿ’–

  • pathName xview โ€” no args, no drama, just receipts. Returns a list of two elements, and each element is a real fraction between 0 and 1. Together they describe the horizontal span that's visible in the window. So like, if the first element is .2 and the second element is .6, then 20% of the canvas's area (as defined by the -scrollregion option) is off-screen to the left, the middle 40% is visible in the window, and 40% of the canvas is off-screen to the right. These are the same values passed to scrollbars via the -xscrollcommand option. iykyk โœจ
  • pathName xview moveto fraction โ€” adjusts the view in the window so that fraction of the total width of the canvas is off-screen to the left. Fraction must be a fraction between 0 and 1. periodt.
  • pathName xview scroll number what โ€” shifts the view in the window left or right according to number and what. Number must be an integer or a float, but if it is a float then it is converted to an integer, rounded away from 0. What must be either pages or units or an abbreviation of one of these. If what is pages then the view adjusts in units of nine-tenths the window's width. If number is negative then information farther to the left becomes visible; if it's positive then information farther to the right becomes visible. If what is units, the view adjusts left or right in units of the xScrollIncrement option, if it's greater than zero, or in units of one-tenth the window's width otherwise. slay ๐Ÿฆ‹

pathName yview ?args? ๐ŸŽ€

This command is used to query and change the vertical position of the information displayed in the canvas's window. It can take any of the following forms:

  • pathName yview โ€” returns a list containing two elements. Each element is a real fraction between 0 and 1; together they describe the vertical span that's visible in the window. For example, if the first element is .6 and the second element is 1.0, the lowest 40% of the canvas's area (as defined by the -scrollregion option) is visible in the window. These are the same values passed to scrollbars via the -yscrollcommand option.
  • pathName yview moveto fraction โ€” adjusts the view in the window so that fraction of the canvas's area is off-screen to the top. Fraction is a fraction between 0 and 1.
  • pathName yview scroll number what โ€” this command adjusts the view in the window up or down according to number and what. Number must be an integer or a float, but if it's a float then it's converted to an integer, rounded away from 0. What must be either pages or units. If what is pages then the view adjusts in units of nine-tenths the window's height. If number is negative then higher information becomes visible; if it's positive then lower information becomes visible. If what is units, the view adjusts up or down in units of the yScrollIncrement option, if it's greater than zero, or in units of one-tenth the window's height otherwise.

๐ŸŒˆ OVERVIEW OF ITEM TYPES ๐ŸŒˆ

The sections below describe the various types of items supported by canvas widgets. Each item type is characterized by two things: first, the form of the create command used to create instances of the type; and second, a set of configuration options for items of that type, which may be used in the create and itemconfigure widget commands. Most items do not support indexing or selection or the commands related to them, such as index and insert. Where items do support these facilities, it's noted explicitly in the descriptions below. At present, text, line and polygon items provide this support. For lines and polygons the indexing facility is used to manipulate the coordinates of the item. ๐Ÿ‘‘


๐Ÿงš COMMON ITEM OPTIONS ๐Ÿงš

Many items share a common set of options. These options are explained here, and then referred to by each widget type for brevity. (bestie we're doing the homework once so we don't have to do it twelve times ๐Ÿ’…)

  • -anchor anchorPos โ€” AnchorPos tells how to position the item relative to the positioning point for the item; it may have any of the forms accepted by Tk_GetAnchor. For example, if anchorPos is center then the item is centered on the point; if anchorPos is n then the item will be drawn so that its top center point is at the positioning point. This option defaults to center. โœจ
  • -dash pattern
  • -activedash pattern
  • -disableddash pattern

Okay so these three are a little trio ๐Ÿซถ โ€” they specify dash patterns for the normal, active state, and disabled state of an item. pattern may have any of the forms accepted by Tk_GetDash. If the dash options are omitted then the default is a solid outline. See DASH PATTERNS for more information.

  • -dashoffset offset โ€” the starting offset in pixels into the pattern provided by the -dash option. -dashoffset is ignored if there is no -dash pattern. The offset may have any of the forms described in the COORDINATES section above.
  • -fill color
  • -activefill color
  • -disabledfill color

These options specify the color to be used to fill the item's area, in its normal, active, and disabled states. The even-odd fill rule is used. Color may have any of the forms accepted by Tk_GetColor. For the line item, it specifies the color of the line drawn. For the text item, it specifies the foreground color of the text. If color is an empty string (the default for all canvas items except line and text), then the item will not be filled. ๐Ÿ’€

  • -outline color
  • -activeoutline color
  • -disabledoutline color

These options specify the color that should be used to draw the outline of the item in its normal, active and disabled states. Color may have any of the forms accepted by Tk_GetColor. If color is specified as an empty string then no outline is drawn for the item.

  • -offset offset โ€” specifies the offset of stipples. The offset value can be of the form x,y or side, where side can be n, ne, e, se, s, sw, w, nw, or center. In the first case the origin is the origin of the toplevel of the current window. For the canvas itself and canvas objects the origin is the canvas origin, but putting # in front of the coordinate pair indicates using the toplevel origin instead. For canvas objects, the -offset option is used for stippling as well. For the line and polygon canvas items you can also specify an index as argument, which connects the stipple origin to one of the coordinate points of the line/polygon.
โš ๏ธ Note that stipple offsets are only supported on X11; they are silently ignored on other platforms. Not a peep. Not a warning. Just vibes.
  • -outlinestipple bitmap
  • -activeoutlinestipple bitmap
  • -disabledoutlinestipple bitmap

These options specify stipple patterns that should be used to draw the outline of the item in its normal, active and disabled states. Indicates that the outline for the item should be drawn with a stipple pattern; bitmap specifies the stipple pattern to use, in any of the forms accepted by Tk_GetBitmap. If the -outline option has not been specified then this option has no effect. If bitmap is an empty string (the default), then the outline is drawn in a solid fashion.

โš ๏ธ Note that stipples are not well supported on platforms that do not use X11 as their drawing API. ๐Ÿ˜ญ
  • -outlineoffset offset โ€” specifies the offset of the stipple pattern used for outlines, in the same way that the -outline option controls fill stipples. (See the -outline option for a description of the syntax of offset.)
  • -stipple bitmap
  • -activestipple bitmap
  • -disabledstipple bitmap

These options specify stipple patterns that should be used to fill the item in its normal, active and disabled states. bitmap specifies the stipple pattern to use, in any of the forms accepted by Tk_GetBitmap. If the -fill option has not been specified then this option has no effect. If bitmap is an empty string (the default), then filling is done in a solid fashion. For the text item, it affects the actual text.

โš ๏ธ Note that stipples are not well supported on platforms that do not use X11 as their drawing API. ๐Ÿ’€
  • -state state โ€” this allows an item to override the canvas widget's global state option. It takes the same values: normal, disabled or hidden.
  • -tags tagList โ€” specifies a set of tags to apply to the item. TagList consists of a list of tag names, which replace any existing tags for the item. TagList may be an empty list.
  • -width outlineWidth
  • -activewidth outlineWidth
  • -disabledwidth outlineWidth

These options specify the width of the outline to be drawn around the item's region, in its normal, active and disabled states. outlineWidth may be in any of the forms described in the COORDINATES section above. If the -outline option has been specified as an empty string then this option has no effect. This option defaults to 1.0. For arcs, wide outlines will be drawn centered on the edges of the arc's region. ๐ŸŽ€


๐ŸŒˆ STANDARD ITEM TYPES ๐ŸŒˆ

Okay bestie, this is the part where we meet the actual items โ€” the little divas that live inside your canvas. Each one has its own create syntax, its own standard-option squad, and its own extra-credit options. Let's go type by type. ๐Ÿ’…


๐Ÿ”ฅ ARC ITEMS ๐Ÿ”ฅ

Arcs show up on your display as... arc-shaped regions, obviously. An arc is a slice of an oval, and that slice is delimited by two angles โ€” you specify those with either the -start and -extent options or with the -height option โ€” and it gets drawn in one of several ways, which is what -style is for.

You make arcs with widget commands shaped like this:

pathName create arc x1 y1 x2 y2 ?option value ...?
pathName create arc coordList ?option value ...?

The args x1, y1, x2, and y2 โ€” or coordList โ€” give the coordinates of two diagonally opposite corners of a rectangular region that encloses the oval defining the arc. (Exception era: that's not the case when -height is specified โ€” more on that below.) After the coordinates you can toss in any number of option-value pairs, each one setting a configuration option for the item. Those same option-value pairs also work inside itemconfigure widget commands to change the item's config. An arc item becomes the current item when the mouse pointer is over any part that's painted โ€” or, when it's fully transparent, over any part that would be painted if both the -fill and -outline options were non-empty. ๐Ÿ‘‘

The standard options that arcs support are:

  • -dash
  • -activedash
  • -disableddash
  • -dashoffset
  • -fill
  • -activefill
  • -disabledfill
  • -offset
  • -outline
  • -activeoutline
  • -disabledoutline
  • -outlineoffset
  • -outlinestipple
  • -activeoutlinestipple
  • -disabledoutlinestipple
  • -stipple
  • -activestipple
  • -disabledstipple
  • -state
  • -tags
  • -width
  • -activewidth
  • -disabledwidth

And here are the extra options arcs get, because they're special like that: โœจ

-extent degrees

Specifies the size of the angular range the arc takes up. The arc's range extends for degrees degrees counter-clockwise from the starting angle given by the -start option. Degrees can be negative, no drama. If it's greater than 360 or less than -360, then degrees modulo 360 is what gets used as the extent. Math is mathing. ๐Ÿงฎ

-start degrees

Specifies the beginning of the angular range the arc occupies. Degrees is in units of degrees, measured counter-clockwise from the 3-o'clock position. Positive or negative, both fine.

-height distance

This one is a shortcut for making a circular arc segment โ€” it defines the distance of the mid-point of the arc from its chord. When you use this option, the coordinates get interpreted as the start and end coordinates of the chord, and -start and -extent are ignored. The value of distance means:

distance > 0 creates a clockwise arc
distance < 0 creates an counter-clockwise arc
distance = 0 creates an arc as if this option had not been
specified

If you want your arc to have a specific radius, r, use this formula:

distance = r ยฑ sqrt(r**2 - (chordLength / 2)**2)

Pick the minus sign for the minor arc and the plus sign for the major arc. ๐Ÿ’ซ

Heads up: itemcget -height always returns 0, so that introspection code can be kept simple. Not a bug, that's just the vibe.

-style type

Specifies how to draw the arc:

  • If type is pieslice (the default), the arc's region is defined by a section of the oval's perimeter plus two line segments โ€” one between the center of the oval and each end of that perimeter section.
  • If type is chord, the arc's region is defined by a section of the oval's perimeter plus a single line segment connecting the two end points of the perimeter section.
  • If type is arc, the arc's region is just a section of the perimeter, alone, no segments. And in this last case the -fill option is ignored. Bye. ๐Ÿ‘‹

๐ŸŽ€ BITMAP ITEMS ๐ŸŽ€

Items of type bitmap appear as images with exactly two colors: foreground and background. Iconic, honestly.

Bitmaps are created with widget commands like this:

pathName create bitmap x y ?option value ...?
pathName create bitmap coordList ?option value ...?

The arguments x and y, or coordList (which must have two elements, no more no less), specify the coordinates of a point used to position the bitmap on the display โ€” and that positioning is controlled by the -anchor option. After the coordinates you can add any number of option-value pairs, each setting a configuration option for the item. Those same option-value pairs work in itemconfigure widget commands to change the item's config. A bitmap item becomes the current item when the mouse pointer is over any part of its bounding box. ๐Ÿฆ‹

The standard options supported by bitmaps are:

  • -anchor
  • -state
  • -tags

The extra options bitmaps get:

-background color

-activebackground color

-disabledbackground color

Specifies the color to use for each of the bitmap's โ€œ0โ€ valued pixels, in its normal, active and disabled states respectively. Color can have any of the forms accepted by Tk_GetColor. If this option isn't specified, or if it's specified as an empty string, then nothing is displayed where the bitmap pixels are 0 โ€” which gives you a transparent effect. Cute! โœจ

-bitmap bitmap

-activebitmap bitmap

-disabledbitmap bitmap

These options specify the bitmaps to display in the item in its normal, active and disabled states. Bitmap can have any of the forms accepted by Tk_GetBitmap.

-foreground color

-activeforeground color

-disabledforeground color

These options specify the color to use for each of the bitmap's โ€œ1โ€ valued pixels, in its normal, active and disabled states. Color can have any of the forms accepted by Tk_GetColor.


๐Ÿฆ‹ IMAGE ITEMS ๐Ÿฆ‹

Items of type image are for displaying images on a canvas. Main character energy, frankly. ๐ŸŒธ

Images are created with widget commands of this form:

pathName create image x y ?option value ...?
pathName create image coordList ?option value ...?

The arguments x and y, or coordList, specify the coordinates of a point used to position the image on the display โ€” controlled by the -anchor option, same as bitmaps. After the coordinates there may be any number of option-value pairs, each of which sets one of the configuration options for the item. These same option-value pairs may be used in itemconfigure widget commands to change the item's configuration. An image item becomes the current item when the mouse pointer is over any part of its bounding box.

The standard options supported by images are:

  • -anchor
  • -state
  • -tags

The extra options images get:

-image name

-activeimage name

-disabledimage name

Specifies the name of the images to display in the item in is normal, active and disabled states. This image must have been created previously with the image create command. No pre-creating, no displaying. Periodt. ๐Ÿ’…


๐ŸŒŸ LINE ITEMS ๐ŸŒŸ

Items of type line appear on the display as one or more connected line segments or curves. Line items support coordinate indexing operations using the dchars, index and insert widget commands โ€” so you can mess with individual points. ๐Ÿ”ฅ

Lines are created with widget commands of the following form:

pathName create line x1 y1... xn yn ?option value ...?
pathName create line coordList ?option value ...?

The arguments x1 through yn, or coordList, give the coordinates for a series of two or more points that describe a series of connected line segments. After the coordinates there may be any number of option-value pairs, each of which sets one of the configuration options for the item. These same option-value pairs may be used in itemconfigure widget commands to change the item's configuration. A line item is the current item whenever the mouse pointer is over any segment of the line โ€” whether drawn or not, and whether or not the line is smoothed. Yes, even the invisible bits count. ๐Ÿ˜ญ

The standard options supported by lines are:

  • -dash
  • -activedash
  • -disableddash
  • -dashoffset
  • -fill
  • -activefill
  • -disabledfill
  • -stipple
  • -activestipple
  • -disabledstipple
  • -state
  • -tags
  • -width
  • -activewidth
  • -disabledwidth

The extra options lines get:

-arrow where

Indicates whether or not arrowheads are to be drawn at one or both ends of the line. Where must have one of the values none (for no arrowheads), first (for an arrowhead at the first point of the line), last (for an arrowhead at the last point of the line), or both (for arrowheads at both ends). This option defaults to none.

When requested to draw an arrowhead, Tk internally adjusts the corresponding line end point so that the rendered line ends at the neck of the arrowhead rather than at its tip โ€” that way the line doesn't extend past the edge of the arrowhead. โš ๏ธ This may trigger a Leave event if the mouse is hovering that line end. And conversely, when removing an arrowhead, Tk adjusts the corresponding line point the other way round, which may trigger an Enter event. Sneaky little side effects, iykyk.

-arrowshape shape

This option indicates how to draw arrowheads. The shape argument must be a list with three elements, each specifying a distance in any of the forms described in the COORDINATES section above. Here's the breakdown, in order:

  1. The first element of the list gives the distance along the line from the neck of the arrowhead to its tip.
  2. The second element gives the distance along the line from the trailing points of the arrowhead to the tip.
  3. The third element gives the distance from the outside edge of the line to the trailing points.

If this option isn't specified, then Tk picks a โ€œreasonableโ€ shape. Trust the algorithm bestie. ๐Ÿซถ

-capstyle style

Specifies the ways in which caps are to be drawn at the endpoints of the line. Style may have any of the forms accepted by Tk_GetCapStyle (butt, projecting, or round). If this option isn't specified then it defaults to butt. Where arrowheads are drawn, the cap style is ignored. ๐Ÿ’€

  • -joinstyle style โ€” this is the glow-up for your corners, bestie ๐Ÿ’… it tells Tk how to draw the joints where the line's vertices meet. style can be any of the forms that Tk_GetJoinStyle accepts โ€” that's bevel, miter, or round. Leave it out and it lowkey just defaults to round. And heads up: if your line only has two points, this option is literally irrelevant (no vertices to join, no drama ๐Ÿซ ).
  • -smooth smoothMethod โ€” smoothMethod has to be either one of the forms Tcl_GetBoolean accepts, or a line smoothing method. In the core only true and raw are supported (with bezier being an alias for true), but more can be added at runtime, so the vibes can expand โœจ. If you pass a boolean false value or an empty string, no smoothing happens at all โ€” flat, unbothered, at peace. A boolean truth value assumes true smoothing.

So if the smoothing method is true, the line gets drawn as a curve, rendered as a set of quadratic splines: one spline for the first and second line segments, one for the second and third, and so on, forever, like a group chat that never ends. You can still get straight-line segments inside a curve by duplicating the end-points of the desired line segment. Very "I'm curved but I contain multitudes."

If the smoothing method is raw, the line also gets drawn as a curve, BUT the coordinate list has to be set up so that the first coordinate pair (and every third coordinate pair after that) is a knot point on a cubic Bezier curve, and the other coordinates are control points on that cubic Bezier curve. Straight line segments can be generated within a curve by making control points equal to their neighbouring knot points. And if the last point is a control point and not a knot point, the point gets repeated (one or two times) so that it also becomes a knot point. Periodt ๐Ÿ”ฅ

  • -splinesteps number โ€” how smooth do you want those curves, queen? Each spline gets approximated with number line segments. This option is ignored unless -smooth is true or raw, so if you're not smoothing, don't even worry about it ๐Ÿ™ˆ.

๐Ÿฅš OVAL ITEMS ๐Ÿฅš

Items of type oval show up as circular or oval regions on the display. Each oval can have an outline, a fill, or both โ€” choose your aesthetic ๐ŸŒธ.

Ovals are created with widget commands shaped like this:

pathName create oval x1 y1 x2 y2 ?option value ...?
pathName create oval coordList ?option value ...?

The arguments x1, y1, x2, and y2, or coordList, give the coordinates of two diagonally opposite corners of a rectangular region that encloses the oval. The oval includes the top and left edges of that rectangle, but not the lower or right edges โ€” it's giving selective, and honestly, same. If the region is square, the resulting oval is circular; otherwise it gets elongated in shape.

After the coordinates you can drop any number of option-value pairs, each one setting a configuration option for the item. Those exact same option-value pairs can be used in itemconfigure widget commands to change the item's configuration later โ€” glow-up on demand ๐Ÿ’–.

An oval item becomes the current item when the mouse pointer is over any part that's painted, or (when it's fully transparent) any part that would be painted if both the -fill and -outline options were non-empty. iykyk.

The following standard options are supported by ovals:

  • -dash
  • -activedash
  • -disableddash
  • -dashoffset
  • -fill
  • -activefill
  • -disabledfill
  • -offset
  • -outline
  • -activeoutline
  • -disabledoutline
  • -outlineoffset
  • -outlinestipple
  • -activeoutlinestipple
  • -disabledoutlinestipple
  • -stipple
  • -activestipple
  • -disabledstipple
  • -state
  • -tags
  • -width
  • -activewidth
  • -disabledwidth

There are no oval-specific options. Not one. An oval is an oval, bestie, she needs nothing extra ๐ŸŽ€


๐Ÿ”ท POLYGON ITEMS ๐Ÿ”ท

Items of type polygon appear as polygonal or curved filled regions on the display. Polygon items support coordinate indexing operations using the dchars, index, and insert widget commands โ€” so you can absolutely edit them point by point โœจ.

Polygons are created with widget commands shaped like this:

pathName create polygon x1 y1 ... xn yn ?option value ...?
pathName create polygon coordList ?option value ...?

The arguments x1 through yn, or coordList, specify the coordinates for three or more points that define a polygon. Here's the thing though: do not repeat the first point as the last point to close the shape โ€” Tk will automatically close the periphery between the first and last points for you. Not me doing extra work for no reason ๐Ÿ˜ญ

After the coordinates there can be any number of option-value pairs, each one setting a configuration option for the item, and those same pairs work in itemconfigure widget commands to change the item's configuration. A polygon item is the current item whenever the mouse pointer is over any part of the polygon โ€” whether drawn or not, and whether or not the outline is smoothed. She's confident. She doesn't need to be visible to be present ๐Ÿ’…

The following standard options are supported by polygons:

  • -dash
  • -activedash
  • -disableddash
  • -dashoffset
  • -fill
  • -activefill
  • -disabledfill
  • -offset
  • -outline
  • -activeoutline
  • -disabledoutline
  • -outlineoffset
  • -outlinestipple
  • -activeoutlinestipple
  • -disabledoutlinestipple
  • -stipple
  • -activestipple
  • -disabledstipple
  • -state
  • -tags
  • -width
  • -activewidth
  • -disabledwidth

The following extra options are supported for polygons:

  • -joinstyle style โ€” the corners of the outline get their moment ๐Ÿ‘‘ this specifies the ways joints are drawn at the vertices of the outline. style may have any of the forms accepted by Tk_GetJoinStyle (bevel, miter, or round). If you don't specify it, it defaults to round.
  • -smooth boolean โ€” boolean must have one of the forms accepted by Tcl_GetBoolean, or be a line smoothing method. Only true and raw are supported in the core (with bezier being an alias for true), but more can be added at runtime, because growth is beautiful ๐Ÿฆ‹. If a boolean false value or an empty string is given, no smoothing is applied. A boolean truth value assumes true smoothing.

If the smoothing method is true, the polygon is drawn as a curve, rendered as a set of quadratic splines: one spline for the first and second line segments, one for the second and third, and so on down the line. Straight-line segments can still be generated within a curve by duplicating the end-points of the desired line segment.

If the smoothing method is raw, the polygon is also drawn as a curve, but the coordinate list has to be such that the first coordinate pair (and every third coordinate pair thereafter) is a knot point on a cubic Bezier curve, and the other coordinates are control points on that cubic Bezier curve. Straight line segments can be generated within a curve by making control points equal to their neighbouring knot points. And if the last point is not the second point of a pair of control points, the point is repeated (one or two times) so that it also becomes the second point of a pair of control points โ€” the associated knot point will be the first control point. Fr fr, that's the rule ๐Ÿ”ฅ

  • -splinesteps number โ€” the degree of smoothness desired for curves: each spline will be approximated with number line segments. This option is ignored unless -smooth is true or raw. Iconic but conditional, periodt.
๐Ÿซถ The polygon is built different. Polygon items are different from other items like rectangles, ovals, and arcs, in that interior points are considered to be "inside" a polygon (for purposes of the find closest and find overlapping widget commands, for example) even if it is not filled. For most other item types, an interior point counts as inside only if the item is filled, or if it has neither a fill nor an outline. So if you want an unfilled polygon whose interior points are not considered inside the polygon, use a line item instead. Choose your own adventure ๐Ÿ’œ

๐ŸŸฆ RECTANGLE ITEMS ๐ŸŸฆ

Items of type rectangle appear as rectangular regions on the display. Each rectangle may have an outline, a fill, or both. Simple. Clean. Structured. Main character energy ๐Ÿ“โœจ

Rectangles are created with widget commands shaped like this:

pathName create rectangle x1 y1 x2 y2 ?option value ...?
pathName create rectangle coordList ?option value ...?

The arguments x1, y1, x2, and y2, or coordList (which must have four elements), give the coordinates of two diagonally opposite corners of the rectangle. The rectangle includes its upper and left edges but not its lower or right edges โ€” again with the selective edges, and honestly it's a whole vibe.

After the coordinates there may be any number of option-value pairs, each of which sets one of the configuration options for the item. These same option-value pairs may be used in itemconfigure widget commands to change the item's configuration. A rectangle item becomes the current item when the mouse pointer is over any part that is painted, or (when fully transparent) any part that would be painted if both the -fill and -outline options were non-empty. Same energy as the oval, and we love consistency ๐Ÿซถ

The following standard options are supported by rectangles:

  • -dash
  • -activedash
  • -disableddash
  • -dashoffset
  • -fill
  • -activefill
  • -disabledfill
  • -offset
  • -outline
  • -activeoutline
  • -disabledoutline
  • -outlineoffset
  • -outlinestipple
  • -activeoutlinestipple
  • -disabledoutlinestipple
  • -stipple
  • -activestipple
  • -disabledstipple
  • -state
  • -tags
  • -width
  • -activewidth
  • -disabledwidth

There are no rectangle-specific options. Four corners, that's it, that's the whole personality ๐ŸŒˆ

๐ŸŒธ TEXT ITEMS ๐ŸŒธ

A text item is literally just a string of characters vibing on the screen, in one line or several. Bestie, text items are the main characters of indexing, editing and selection โ€” they get all of that through the dchars widget command, the focus widget command, the icursor widget command, the index widget command, the insert widget command, and the select widget command. Text items are created with widget commands that look exactly like this:

pathName create text x y ?option value ...?
pathName create text coordList ?option value ...?

The arguments x and y, or coordList (which must have two elements, no negotiations ๐Ÿ’…), specify the coordinates of a point used to position the text on the display โ€” peep the options below for the tea on how text actually gets displayed. After the coordinates there may be any number of option-value pairs, each of which sets one of the configuration options for the item. These same option-value pairs may be used in itemconfigure widget commands to change the item's configuration. A text item becomes the current item when the mouse pointer is over any part of its bounding box. ๐ŸŽ€

The following standard options are supported by text items:

  • -anchor
  • -fill
  • -activefill
  • -disabledfill
  • -stipple
  • -activestipple
  • -disabledstipple
  • -state
  • -tags

And here are the extra options, the lil bonus ones, the โœจ garnish โœจ, supported for text items:

  • -angle rotationDegrees โ€” RotationDegrees tells you how many degrees to rotate the text anticlockwise about the positioning point for the text, bestie. It may have any floating-point value from 0.0 to 360.0. So for example, if rotationDegrees is 90, then the text will be drawn vertically from bottom to top. ๐ŸŒˆ This option defaults to 0.0.
  • -font fontName โ€” specifies the font to use for the text item. FontName may be any string acceptable to Tk_GetFont. If this option is not specified, it defaults to a system-dependent font. iykyk ๐Ÿฆ‹
  • -justify how โ€” specifies how to justify the text within its bounding region. How must be one of the values left, right, or center. This option will only matter if the text is displayed as multiple lines (so, single-line girlies, don't even stress). If the option is omitted, it defaults to left.
  • -text string โ€” String specifies the characters to be displayed in the text item. Newline characters cause line breaks. The characters in the item may also be changed with the insert and delete widget commands. This option defaults to an empty string.
  • -underline number โ€” specifies the integer index of a character within the text to be underlined. 0 corresponds to the first character of the text displayed, 1 to the next character, and so on. -1 means that no underline should be drawn โ€” and heads up, if the whole text item is to be underlined, the appropriate font should be used instead. ๐Ÿ‘‘
  • -width lineLength โ€” specifies a maximum line length for the text, in any of the forms described in the COORDINATES section above. If this option is zero (the default) the text is broken into lines only at newline characters. However, if this option is non-zero then any line that would be longer than lineLength is broken just before a space character to make the line shorter than lineLength; the space character is treated as if it were a newline character. Not me wrapping your text for you ๐Ÿ˜ญ

๐ŸชŸ WINDOW ITEMS ๐ŸชŸ

Items of type window cause a particular window to be displayed at a given position on the canvas. Window items are created with widget commands of the following form:

pathName create window x y ?option value ...?
pathName create window coordList ?option value ...?

The arguments x and y, or coordList (which must have two elements), specify the coordinates of a point used to position the window on the display, as controlled by the -anchor option. After the coordinates there may be any number of option-value pairs, each of which sets one of the configuration options for the item. These same option-value pairs may be used in itemconfigure widget commands to change the item's configuration. Theoretically, a window item becomes the current item when the mouse pointer is over any part of its bounding box โ€” but in practice this typically does not happen, because the mouse pointer ceases to be over the canvas at that point. ๐Ÿ’€ it's giving "we tried".

The following standard options are supported by window items:

  • -anchor
  • -state
  • -tags

The following extra options are supported for window items:

  • -height pixels โ€” specifies the height to assign to the item's window. Pixels may have any of the forms described in the COORDINATES section above. If this option is not specified, or if it is specified as zero, then the window is given whatever height it requests internally. Let it cook, fr fr.
  • -width pixels โ€” specifies the width to assign to the item's window. Pixels may have any of the forms described in the COORDINATES section above. If this option is not specified, or if it is specified as zero, then the window is given whatever width it requests internally. Same energy, different axis. ๐ŸŒธ
  • -window pathName โ€” specifies the window to associate with this item. The window specified by pathName must either be a child of the canvas widget or a child of some ancestor of the canvas widget. PathName may not refer to a top-level window. Periodt. ๐Ÿšซ
โš ๏ธ Okay so important note, no cap: due to restrictions in the ways that windows are managed, it is not possible to draw other graphical items (such as lines and images) on top of window items. A window item always obscures any graphics that overlap it, regardless of their order in the display list. Also note that window items, unlike other canvas items, are not clipped for display by their containing canvas's border, and are instead clipped by the parent widget of the window specified by the -window option; when the parent widget is the canvas, this means that the window item can overlap the canvas's border. Iconic behaviour honestly ๐Ÿ’…

๐Ÿ’– APPLICATION-DEFINED ITEM TYPES ๐Ÿ’–

It is possible for individual applications to define new item types for canvas widgets using C code. See the documentation for Tk_CreateItemType. Go off, build your own, we support you ๐Ÿซถ


โœจ BINDINGS โœจ

In the current implementation, new canvases are not given any default behavior: you will have to execute explicit Tcl commands to give the canvas its behavior. No autopilot bestie, you're driving. ๐Ÿš—


๐Ÿ† CREDITS ๐Ÿ†

Tk's canvas widget is a blatant ripoff of ideas from Joel Bartlett's ezd program. Ezd provides structured graphics in a Scheme environment and preceded canvases by a year or two. Its simple mechanisms for placing and animating graphical objects inspired the functions of canvases. Respect where it's due, honestly โ€” the blueprint was right there. ๐Ÿ‘‘


๐Ÿ‘€ SEE ALSO ๐Ÿ‘€


๐Ÿ”‘ KEYWORDS ๐Ÿ”‘

  • canvas
  • widget

And that's a wrap on the whole page, bestie!! ๐ŸŽ€ This beauty comes to you from Tk 8.3, dated back in the day, and it lives in the manual as canvas(n). Now go forth and draw things. Slay. ๐Ÿ’–โœจ

๐Ÿ“ฆ where this page comes from
  • fedora 43: tk 1:9.0.2-2.fc43 ยท TCL AND HPND-Pbmplus AND CC-BY-SA-3.0 AND MIT-open-group AND MIT
  • fedora 43: tk 1:9.0.2-2.fc43 ยท TCL AND HPND-Pbmplus AND CC-BY-SA-3.0 AND MIT-open-group AND MIT
  • fedora 44: tk 1:9.0.2-2.fc44 ยท TCL AND HPND-Pbmplus AND CC-BY-SA-3.0 AND MIT-open-group AND MIT
  • fedora 44: tk 1:9.0.2-2.fc44 ยท TCL AND HPND-Pbmplus AND CC-BY-SA-3.0 AND MIT-open-group AND MIT
  • ๐Ÿ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms