canvas(3tk)
๐จ NAME ๐จ
okay bestie, welcome to canvas โ this is the Tk built-in command page for it, and it's a big one. What it does: create and manipulate canvas hypergraphics drawing surface widgets ๐
โจ
๐ SYNOPSIS ๐
canvas pathName ?options?
โจ STANDARD OPTIONS โจ
These are the regular ones every self-respecting widget gets, no cap:
-background-borderwidth-cursor-highlightbackground-highlightcolor-highlightthickness-insertbackground-insertborderwidth-insertofftime-insertontime-insertwidth-relief-selectbackground-selectborderwidth-selectforeground-takefocus-xscrollcommand-yscrollcommand
For the whole tea on these, go read the options manual entry. It's right there. I'm not gonna re-explain them, that's not my job today.
๐ WIDGET-SPECIFIC OPTIONS ๐
These ones are hers. Only canvas has them. Obsessed.
-closeenough
- Database Name:
closeEnough - Database Class:
CloseEnough
Sets a floating-point value for how close the mouse cursor has to be to an item before we count it as being โinsideโ that item. Defaults to 1.0.
-confine
- Database Name:
confine - Database Class:
Confine
A boolean, and it decides whether you're even allowed to set the canvas's view outside the region defined by the scrollRegion argument. Defaults to true โ meaning yeah, the view gets constrained to stay inside the scroll region. Good luck escaping bestie, you can't.
-height
- Database Name:
height - Database Class:
Height
The window height the canvas widget wants to request from its geometry manager. You can write the value in any of the forms described down in the COORDINATES section. ๐
-scrollregion
- Database Name:
scrollRegion - Database Class:
ScrollRegion
A list of four coordinates: left, top, right, and bottom of a rectangular region. This region is what scrolling is based on, and it counts as the boundary of the information in the canvas. Each coordinate can be written in any of the forms given in the COORDINATES section below. ๐
-state
- Database Name:
state - Database Class:
State
Changes the default state of the canvas. state can be one of: normal, disabled, or hidden. Every individual canvas object has its own state option too, and that one can override the default. Lots of options can take separate specifications, so an item's appearance can differ depending on the situation. The options starting with active control how it looks when the mouse pointer is over it, and the option starting with disabled controls how it looks when the state is disabled. Important: canvas items that are disabled will not react to canvas bindings. Periodt.
-width
- Database Name:
width - Database Class:
width
The window width the canvas widget wants to request from its geometry manager. Value can be in any of the forms described in the COORDINATES section below.
-xscrollincrement
- Database Name:
xScrollIncrement - Database Class:
ScrollIncrement
An increment for horizontal scrolling, in any of the usual forms allowed for screen distances. If this value is greater than zero, the horizontal view in the window gets constrained so the canvas x coordinate at the left edge of the window is always an even multiple of xScrollIncrement. Also the units for scrolling (like, the change in view when you hit the left and right arrows of a scrollbar) become xScrollIncrement too. If the value is negative or zero, horizontal scrolling is unconstrained โ free range, do what you want. ๐ฆ
-yscrollincrement
- Database Name:
yScrollIncrement - Database Class:
ScrollIncrement
Same energy but vertical. An increment for vertical scrolling, in any of the usual forms allowed for screen distances. If it's greater than zero, the vertical view gets constrained so the canvas y coordinate at the top edge of the window is always an even multiple of yScrollIncrement, and the units for scrolling (e.g. the change in view when the top and bottom arrows of a scrollbar get selected) are yScrollIncrement too. If the value is negative or zero, vertical scrolling is unconstrained.
๐ธ INTRODUCTION ๐ธ
So. The canvas command makes a brand new window (that's your pathName argument) and turns it into a canvas widget. You can pass extra options โ the ones listed above โ either on the command line or through the option database, and those configure stuff like the canvas's colors and its 3-D relief. The canvas command returns its pathName argument back to you. ๐ซถ
โ ๏ธ Timing matters here: at the moment you invoke this command, a window namedpathNamemust not already exist. ButpathName's parent does have to exist. That's the rule, don't fight it.
Canvas widgets do structured graphics. A canvas can display any number of items โ things like rectangles, circles, lines, and text. You can manipulate those items (move them, re-color them, etc.) and you can associate commands with items pretty much the same way the bind command lets you bind commands to widgets. For example, you could hook a particular command to the <Button-1> event so it fires whenever button 1 gets pressed while the mouse cursor is over an item. Which means: items in a canvas can have behaviors defined by the Tcl scripts bound to them. Main character energy, honestly. ๐
๐ฆ DISPLAY LIST ๐ฆ
Items in a canvas are ordered for display purposes. The first item in the display list is displayed first, then the next one in the list, and so on down the line. Items that come later in the display list obscure the ones that came earlier โ people sometimes say the later ones are โon topโ of the earlier items. When you create a new item, it gets placed at the end of the display list, on top of everything else. Widget commands can re-arrange the order of the display list whenever you want.
Window items are the exception to all of that. The underlying window systems require them to always be drawn on top of other items. On top of that (lol), the stacking order of window items is not affected by any of the canvas widget commands โ for that you have to use Tk's raise command and lower command instead. ๐
๐ท๏ธ ITEM IDS AND TAGS ๐ท๏ธ
Items in a canvas widget can be named two ways: by id or by tag.
Every item gets a unique identifying number, assigned when the item is created. The id of an item never changes, and id numbers are never re-used within the lifetime of a canvas widget. Iconic, honestly.
Each item can also have any number of tags attached. A tag is just a string of characters, and it can take any form โ with one exception: it can't be an integer. So like, x123 is fine but 123 is not. The same tag can be associated with many different items, and people do that all the time to group items in fun and interesting ways. Classic move: give every selected item the tag selected. ๐
The tag all is implicitly associated with every single item in the canvas, so you can use it to invoke operations on all the items at once. Slay.
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 โ check the individual item type documentation for the details.) If the mouse isn't in the canvas widget, or isn't over an item, then no item has the current tag.
Now, when you're specifying items in canvas widget commands: if the specifier is an integer, it's assumed to refer to the single item with that id. If the specifier is not an integer, it's assumed to refer to all the items in the canvas that have a tag matching that specifier. The symbol tagOrId is used below to mean "this argument is either an id that selects one item, or a tag that selects zero or more items."
tagOrId can also contain a logical expression of tags using these operators: &&, ||, ^, !, and parenthesized subexpressions. Like, for example:
.c find withtag {(a&&!b)||(!a&&b)}
or equivalently:
.c find withtag {a^b}
Both of those will find only the items that have either the a or the b tag, but not both. ๐ cute right?
Some widget commands only operate on one item at a time. If tagOrId is specified in a way that names multiple items, the normal behavior is for the command to use the first (lowest) of those items in the display list that's suitable for the command. Any exceptions get noted in the widget command descriptions below. Keep reading, we're not done here. โญ
๐ธ COORDINATES ๐ธ
okay so every single coordinate in canvas-land is a floating-point number, periodt. no integers-only nonsense here ๐
Coordinates and distances get specified in screen units, which are floating-point numbers that optionally have one of a few little letters tacked on the end. The tea on the letters:
- no letter at all โ distance is in pixels
mโ millimeters on the screencโ centimetersiโ inchespโ printers points (that's 1/72 inch, bestie)
Bigger y-coordinates = points lower on the screen. Bigger x-coordinates = points farther to the right. (yes it's giving "graph paper that starts in the corner", that's just how it is ๐ฆ)
And you can hand over coordinates either as an even number of parameters, or as one single list parameter holding an even number of x and y coordinate values. either way, no cap ๐
โจ TRANSFORMATIONS โจ
So normally the origin of the canvas coordinate system sits at the upper-left corner of the window that contains the canvas. But you can shift that origin around relative to the window origin using the xview and yview widget commands โ which is like, the classic move for scrolling ๐
Canvases do not support scaling or rotation of the canvas coordinate system relative to the window coordinate system. that's just not a thing here, bestie ๐ญ
Individual items though? Those can be moved, scaled or rotated using the widget commands described below. slay ๐
Note that 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 easier to work with. So you only need the canvasx and canvasy widget commands if you adjust the origin of the visible area. iconic design choice
BUT โ and this is the part everyone forgets ๐ โ that also means any focus ring (as controlled by the -highlightthickness option) and window border (as controlled by the -borderwidth option) must be taken into account before you actually get to the visible area of the canvas. do with that what you will ๐
๐ INDICES ๐
Text items support the notion of an index for identifying particular positions within the item. And in a similar fashion, line and polygon items support index 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. iykyk โจ
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 for an index โ and if you're out here defining new types of text-like items, it would be advisable to support as many of these forms as practical. (be a good citizen bestie ๐ซถ)
Note that it is possible to refer to the character just after the last one in the text item; this is necessary for such tasks as inserting new text at the end of the item. ๐
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. (asymmetry? we don't know her)
numberโ A decimal number giving the position of the desired character within the text item.0refers to the first character,1to 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. (math girlie behavior fr fr ๐งฎ)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. it's giving โจaccessorizing your linesโจ
Syntax number one: 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. ๐
Syntax number two: a character list containing only 5 possible characters โ โ.,-_ โ. 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:
-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 with 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. consistency queen ๐
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. ๐ช๐ญ
๐ 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 *arg*s 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 (it's giving "no thoughts, no items, no problem" ๐). 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 last one of them, periodt ๐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. (circular scrolling, we love her ๐)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. (yes, the order matters, don't test it ๐)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. (this one's the generous one ๐)withtag tagOrIdโ Selects all the items given by tagOrId.
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 giving "close enough bestie" ๐ญ)
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 one is the main character of canvas interactivity ๐
โ it ties command to all the items you name with tagOrId, so that every time the event sequence in sequence happens on one of those items, command gets called. Basically it's the bind command but for canvas items instead of whole widgets. Slay.
For the full tea on how sequence is written and what substitutions get done to command before it runs, go read the bind manual entry โ that's where all that lives. ๐ซถ
So here's the deal with arguments:
- All args present โ a brand new binding gets created, and it replaces any existing binding for the same
sequenceandtagOrId. Unless the first character ofcommandis+, in which casecommandaugments the existing binding instead of yeeting it. Return value in this case? Empty string. Nothing to see. โจ commandomitted โ you get back the command associated withtagOrIdandsequence. And bestie, if there's no such binding, that's an error. ๐- Both
commandandsequenceomitted โ you get a list of all the sequences that have bindings defined fortagOrId. A whole little catalog. Obsessed.
Now the vibe check on which events are even allowed: only stuff related to the mouse and keyboard (think Enter, Leave, Button, Motion, and Key) or virtual events. That's it. That's the list.
Canvas event handling runs on the current item (the one described up in ITEM IDS AND TAGS). And heads up, this is lowkey confusing:
EnterandLeaveevents fire for an item when it becomes the current item or stops being the current item. These are not the same asEnterandLeaveevents for windows. Different species, same name. ๐ฆ
- Mouse-related events get directed to the current item, if there is one.
- Keyboard-related events get directed to the focus item, if there is one (more on this in the
focuswidget command down below). - 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.
Multiple bindings matching one event? Extremely possible, no cap. Like, one binding could be tied to the item's id and another tied to one of the item's tags. When that happens, all the matching bindings get invoked, in this exact order:
- A binding associated with the
alltag goes first. - Then one binding for each of the item's tags, in order.
- Then a binding associated with the item's id.
And if there are multiple matching bindings for a single tag, only the most specific binding gets invoked. Periodt.
Inside a binding script, continue terminates that script, and break terminates that script and skips any remaining scripts for the event โ exactly like the bind command does it.
One more thing bestie, don't get it twisted: if bindings were made for a canvas window using the bind command, those get invoked in addition to the ones made for the canvas's items with the bind widget command. And the item bindings go first, before any of the window-as-a-whole bindings. Order matters, always. ๐
pathName canvasx screenx ?gridspacing?
Hand it a window x-coordinate in screenx and it gives you back the canvas x-coordinate being displayed at that spot. If you pass gridspacing, the canvas coordinate gets rounded to the nearest multiple of gridspacing units. Snapped. Clean. โจ
pathName canvasy screeny ?gridspacing?
Same energy, y-axis edition ๐ธ โ give it a window y-coordinate in screeny and it returns the canvas y-coordinate displayed there. And yeah, if gridspacing is specified, the canvas coordinate rounds to the nearest multiple of gridspacing units.
pathName cget option
Returns the current value of the configuration option named by option. And option can be any of the values the canvas command accepts. Simple. Iconic. ๐
pathName configure ?option? ?value? ?option value ...?
Query or modify the widget's configuration options, choose your adventure:
- No
optionโ returns a list describing all the available options forpathName. (CheckTk_ConfigureInfofor the format of that list, iykyk.) optionwith novalueโ returns a list describing just that one named option. Fun fact: this list is identical to the corresponding sublist of what you'd get with nooptionspecified. Same info, smaller serving. ๐- One or more
option-valuepairs โ the command modifies the given widget option(s) to have the given value(s). Return value here is an empty string. Bye. ๐
Either way, option may have any of the values accepted by the canvas command.
pathName coords tagOrId ?x0 y0 ...?
pathName coords tagOrId ?coordList?
Query or modify the coordinates that define an item. Here's the breakdown:
- No coordinates given โ returns a list whose elements are the coordinates of the item named by
tagOrId. - Coordinates given โ they replace the current coordinates of the named item.
- If
tagOrIdrefers to multiple items, only the first one in the display list gets used. First come, first served, bestie.
โ ๏ธ Now the important caveats, pay attention: For rectangles, ovals and arcs, the returned coordinate list has a fixed order: left, top, right, bottom. That may not be the order you originally gave them in. So don't come for me. ๐ญ 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 or whatever, the returned values will still be pixels. No conversion back. That's just how it is. ๐
pathName create type x y ?x y ...? ?option value ...?
pathName create type coordList ?option value ...?
Creates a brand new item in pathName of type type. ๐
The exact format of the arguments after type depends on type, but usually it's the coordinates for one or more points, followed by specs for zero or more item options. For all the juicy syntax details on this command, go check the subsections on the individual item types further down. And the return value? The id of the new item. Keep it, you'll need it. ๐ซถ
pathName dchars tagOrId first ?last?
For every item given by tagOrId, deletes the characters โ or coordinates โ in the range from first to last, inclusive.
- If some of the items given by
tagOrIddon't support indexing operations, they just ignore this operation entirely. Not their business. ๐ Textitems readfirstandlastas indices to a character.lineandpolygonitems read them as indices to a coordinate (an x,y pair).- Indices themselves are described up in INDICES.
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. That's it, that's the whole thing. Gone. Poof. ๐จ
pathName dtag tagOrId ?tagToDelete?
For each item given by tagOrId, deletes the tag named tagToDelete from that item's list of associated tags. If an item doesn't have the tag tagToDelete, that item is simply unaffected by the command โ 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 given by searchCommand and its args. searchCommand and the args can be any of the forms the addtag command accepts. And the items come back in stacking order, lowest item first. ๐
pathName focus ?tagOrId?
Sets the keyboard focus for the canvas widget onto the item given by tagOrId. Let's get into it:
- If
tagOrIdrefers to several items, focus goes to the first such item in the display list that supports the insertion cursor. - If
tagOrIdrefers to no items, or if none of them support the insertion cursor, then the focus is not changed. Stay put. ๐ - If
tagOrIdis an empty string, the focus item gets reset so that no item has the focus. - If
tagOrIdis not specified at all, the command returns the id of 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. โจ
๐จ Now this part is so important and it trips people up constantly: The focus item within a canvas and the focus window on the screen (the one set with thefocuscommand) are totally independent. A given item doesn't actually have the input focus unless both of these are true: 1. its canvas is the focus window, and 2. the item is the focus item within the canvas. In most cases it is advisable to follow thefocuswidget command with thefocuscommand to set the focus window to the canvas โ if it wasn't already there. Do both, bestie. Future you will be grateful. ๐ซถ
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. And if tagOrId refers to no items at all, or the item has no tags, you get an empty string back. Nada. ๐
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 โ they just sit there unbothered. See INDICES above for all the legal forms of index.
Heads up: 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 be set even when the item doesn't have the focus. So you can pre-position it, it just won't show. ๐
This command returns an empty string.
pathName image imagename ?subsample? ?zoom?
Draws the canvas into the Tk photo image named imagename. ๐ผ๏ธ
- If a
-scrollregionhas been defined, then that will be the boundaries of the canvas region drawn, and the final size of the photo image. - Otherwise, the widget width and height with an origin of
0,0will be 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 will be reduced in size.
So like โ continuing that image command energy: on top of the subsample, you can also pass an integer zoom factor, and the photo image will get enlarged. ๐ซถ The image background gets filled with the canvas background colour. And here's the important bit, bestie: the canvas widget does not need to be mapped for this widget command to work, but at least one of its ancestors must be mapped.
This command returns an empty string.
pathName imove tagOrId index x y
This one relocates the index'th coordinate of every single item pointed at by tagOrId over to the location (x,y). Each item interprets index all independently, following the rules laid out in INDICES above. And out of the whole standard item set? Only line and polygon items are allowed to have their coordinates relocated this way. That's it, that's the guest list. ๐
pathName index tagOrId index
Returns a decimal string โ the numerical index within tagOrId that lines up with index. The index you give is a textual description of the position you want, exactly as described in INDICES above. Text items read index as an index to a character; line and polygon items read it as an index to a coordinate (an x,y pair). The return value is guaranteed to land between 0 and the number of characters, or coordinates, within the item โ inclusive, no cap. ๐ And if tagOrId refers to multiple items? Then the index gets processed in the first of those items that actually supports indexing operations (in display list order).
pathName insert tagOrId beforeThis string
For each of the items given by tagOrId, if the item supports text or coordinate, insertion then string gets inserted into the item's text just 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 (an x,y pair). For lines and polygons the string must be a valid coordinate sequence. No pressure or anything. ๐ญ
Peep INDICES above for the deets on which forms are allowed for beforeThis.
This command returns an empty string.
pathName itemcget tagOrId option
Hands you back the current value of the configuration option for the item given by tagOrId, where that option's name is option. It's basically the cget widget command, except it applies to one particular item instead of the widget as a whole โ glow-up but make it targeted โจ. option can be any of the values accepted by the create widget command back when the item was created. And if tagOrId is a tag pointing at more than one item? The first (lowest) such item is the one that gets used. First come, first served, periodt.
pathName itemconfigure tagOrId ?option? ?value? ?option value ...?
Same vibe as the configure widget command, except it tweaks item-specific options for the items given by tagOrId instead of messing with options for the whole canvas widget. Here's the breakdown:
- If no
optionis specified โ returns a list describing all the available options for the first item given bytagOrId(checkTk_ConfigureInfofor info on the format of this list). - If
optionis specified with novalueโ returns a list describing that one named option (this list will be identical to the corresponding sublist of the value you'd get if no option were specified). - If one or more
option-valuepairs are specified โ the command modifies the given widget option(s) to have the given value(s) in each of the items given bytagOrId; in this case the command 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 โ go read the sections describing individual item types below for the legal options. ๐ง
pathName lower tagOrId ?belowThis?
Moves all of the items given by tagOrId to a new position in the display list, landing just before the item given by belowThis. If tagOrId refers to more than one item then all of them get moved โ but the relative order of the moved items will not change. belowThis is a tag or an id; if it refers to more than one item, then the first (lowest) of those items in the display list is used as the destination for the moved items.
Heads up bestie: this command has no effect on window items. Window items always obscure other item types, and the stacking order of window items is determined by theraisecommand andlowercommand โ not theraisewidget command andlowerwidget command for canvases. Different thing entirely, don't get it twisted. ๐
This command returns an empty string.
pathName move tagOrId xAmount yAmount
Moves each of the items given by tagOrId in the canvas coordinate space by adding xAmount to the x-coordinate of every point associated with the item, and yAmount to the y-coordinate of every point associated with the item. Shifting the whole squad at once, no cap. ๐ฆ
This command 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 (the upper-left corner of the bounding box) of the first item (the lowest in the display list) with tag tagOrId is located at position (xPos,yPos). Both xPos and yPos may be the empty string โ in which case the corresponding coordinate stays unchanged. All items matching tagOrId remain in the same positions relative to each other, so the whole clique travels together. ๐
This command returns an empty string.
pathName postscript ?option value option value ...?
Generates a Postscript representation for part or all of the canvas. Here's how it goes down:
- If the
-fileoption is specified โ the Postscript is written to a file and an empty string is returned. - 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, that's the rules. ๐
If the -channel option is specified, the argument names a channel already opened for writing. The Postscript gets written to that channel, and the channel is left open for further writing at the end of the operation.
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 the screen. If the canvas is freshly created it may still have its initial size of1x1pixel, so nothing will appear in the Postscript. To get around this problem, either invoke theupdatecommand to wait for the canvas window to reach its final size, or else use the-widthand-heightoptions to specify the area of the canvas to print. ๐
The option-value argument pairs give extra info to control the generation of Postscript. These options are supported:
-channelchannelName โ Specifies the name of the channel to which to write the Postscript. If this option and the-fileoption are not specified, then the Postscript is returned as the result of the command.-colormapvarName โvarNamemust be the name of an array variable that specifies a color mapping to use in the Postscript. Each element ofvarNamemust consist of Postscript code to set a particular color value (e.g.1.0 1.0 0.0 setrgbcolor). When outputting color information in the Postscript, Tk checks to see if there's an element ofvarNamewith the same name as the color. If so, Tk uses the value of the element as the Postscript command to set the color. If this option has not been specified, or if there's no entry invarNamefor a given color, then Tk uses the red, green, and blue intensities from the X color.-colormodemode โ Specifies how to output color information.modemust be eithercolor(for full color output),gray(convert all colors to their gray-scale equivalents) ormono(convert all colors to black or white).-filefileName โ Specifies the name of the file in which to write the Postscript. If this option and the-channeloption are not specified, then the Postscript is returned as the result of the command.-fontmapvarName โvarNamemust be the name of an array variable that specifies a font mapping to use in the Postscript. Each element ofvarNamemust consist of a Tcl list with two elements, which are the name and point size of a Postscript font. When outputting Postscript commands for a particular font, Tk checks to see ifvarNamecontains an element with the same name as the font. If there is such an element, then the font information contained in that element is used in the Postscript. Otherwise Tk attempts to guess what Postscript font to use. Tk's guesses generally only work for well-known fonts such as Times and Helvetica and Courier, and only if the X font name does not 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 the dashes to parse the font name).
-heightsize โ Specifies the height of the area of the canvas to print. Defaults to the height of the canvas window.-pageanchoranchor โ Specifies which point of the printed area of the canvas should appear over the positioning point on the page (which is given by the-pagexand-pageyoptions). For example,-pageanchor nmeans that the top center of the area of the canvas being printed (as it appears in the canvas window) should be over the positioning point. Defaults tocenter.-pageheight sizeโ okay so this one scales the Postscript in both x and y so that your printed area comes outsizetall on the page. And what even issize? It's a floating-point number followed bycfor centimeters,ifor inches,mfor millimeters, orpor literally nothing for printer's points (that's 1/72 inch, fyi). Defaults to the height of the printed area on the screen. And here's the tea: if you specify both-pageheightand-pagewidth, then the scale factor from-pagewidthis what actually gets used โ because non-uniform scaling is not implemented. ๐-pagewidth sizeโ same energy, except it scales the Postscript in both x and y so the printed area issizewide on the page.sizehas the exact same form as for-pageheight. Defaults to the width of the printed area on the screen. And yeah, if both-pageheightand-pagewidthare specified then the scale factor from-pagewidthwins (non-uniform scaling is not implemented, we've been over this bestie ๐).-pagex positionโpositiongives the x-coordinate of the positioning point on the Postscript page, and you can use any of the forms allowed for-pageheight. It gets used together with-pagex... no wait, with-pageyand-pageanchorto figure out where the printed area actually lands on the Postscript page. Defaults to the center of the page. ๐ฏ-pagey positionโpositiongives the y-coordinate of the positioning point on the Postscript page, same forms as-pageheight. Works together with-pagexand-pageanchorto decide where the printed area appears on the Postscript page. Defaults to the center of the page. ๐ซถ-rotate booleanโbooleansays 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 the "portrait" orientation, if you were wondering); in rotated output the x-axis runs along the long dimension of the page ("landscape" orientation). Defaults to non-rotated. ๐-width sizeโ specifies the width of the area of the canvas you want to print. Defaults to the width of the canvas window. ๐-x positionโ specifies the x-coordinate of the left edge of the area of the canvas that's getting printed, in canvas coordinates, not window coordinates. Defaults to the coordinate of the left edge of the window.-y positionโ specifies the y-coordinate of the top edge of the area of the canvas to print, again 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 position in the display list, right after the item given by aboveThis. If tagOrId refers to more than one item, then all of them get moved โ but the relative order of the moved items does not change, so don't worry about them getting shuffled. 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 what gets used as the destination. This command returns an empty string.
โ ๏ธ Bestie, listen: 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 theraisecommand andlowercommand โ not by theraisewidget command andlowerwidget command for canvases. iykyk. ๐ญ
๐ pathName rchars tagOrId first last string
This command replaces the text or coordinates between first and last for each of the items indicated by tagOrId with string. Each item interprets first and last independently, following the rules described in INDICES above. Out of the standard set of items, text items support this by altering their text as directed, and line and polygon items support it by altering their coordinate list (in which case string should be a list of coordinates to use as a replacement). The other items just ignore this operation entirely. ๐
๐ 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 operation, and angle identifies the amount to rotate the coordinates anticlockwise, in degrees. (Negative values rotate clockwise, periodt.) This command returns an empty string.
๐ Implementation note: not all item types work the same with rotations. In particular,bitmap,image,textandwindowitems only rotate their anchor points and do not rotate the items themselves about those points, and thearc,ovalandrectangletypes rotate about a computed center point instead of moving the bounding box coordinates directly. So yeah. Be aware.
Some items (currently arc and text) have angles in their options; this command does not affect those options. ๐
๐ 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 operation, and xScale and yScale identify the scale factors for x- and y-coordinates respectively (a scale factor of 1.0 means no change to that coordinate, obviously). For each of the points defining each item, the x-coordinate is adjusted to change the distance from xOrigin by a factor of xScale. Similarly, each y-coordinate is adjusted to change the distance from yOrigin by a factor of yScale. This command returns an empty string.
โจ Note that some items have only a single pair of coordinates (e.g.,text,imagesandwindows) and so scaling them with this command can only move them around. That's just the vibe, ok?
๐ pathName scan option args
This command is used to implement scanning on canvases. It has two forms, depending on option:
pathName scan mark x y
Records x and y and the canvas's current view; used together with later scan dragto commands. Typically this command gets associated with a mouse button press in the widget, and x and y are the coordinates of the mouse. It returns an empty string. ๐ฑ๏ธ
pathName scan dragto x y ?gain?
This one computes the difference between its x and y arguments (which are typically mouse coordinates) and the x and y arguments to the last scan mark command for the widget. Then it adjusts the view by gain times the difference in coordinates, where gain defaults to 10. This command is typically associated with mouse motion events in the widget, to produce the effect of dragging the canvas at high speed through its window. 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 may take any of the forms described below. In all of the descriptions below, tagOrId must refer to an item that supports indexing and selection; if it refers to multiple items then the first of these that supports indexing and the selection is used. Index gives a textual description of a position within tagOrId, as described in INDICES above.
pathName select adjust tagOrId index
Locate the end of the selection in tagOrId nearest to the character given by index, and adjust that end of the selection to be at index (i.e. including but not going beyond index). The other end of the selection is made the anchor point for future select to commands. If the selection is not currently in tagOrId then 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 is not in this widget then the command has no effect at all (iconic, honestly). 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 is not in this canvas then an empty string is returned. Simple as that. ๐
pathName select to tagOrId index
Set the selection to consist of those characters of tagOrId between the selection anchor point and index. The new selection will include the character given by index; it will include 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 is not 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, then the type of the first item in the display list is returned. If tagOrId does not refer to any items at all then an empty string is returned. โจ
โ๏ธ pathName xview ?args?
This command is used to query and change the horizontal position of the information displayed in the canvas's window. It can take any of the following forms:
pathName xviewโ bestie, no args and it just reports on you. You get back a list of two elements, each one a real fraction between 0 and 1, and together they describe the horizontal span that's visible in the window. Like, say the first element is.2and the second is.6? That means 20% of the canvas's area (as defined by the-scrollregionoption) 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. And these are literally the same values passed to scrollbars via the-xscrollcommandoption. 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. That's it, that's the whole vibe.pathName xview scroll number whatโ this command 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's a float then it gets converted to an integer, rounded away from 0 (no sneaky truncation here, she rounds away). What must be eitherpagesorunitsor an abbreviation of one of these. If what ispagesthen 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. And if what isunits, the view adjusts left or right in units of thexScrollIncrementoption, if it's greater than zero, or in units of one-tenth the window's width otherwise. โจpathName yview ?args?โ the vertical sibling, and she serves. 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 these 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.6and the second element is1.0, the lowest 40% of the canvas's area (as defined by the-scrollregionoption) is visible in the window. These are the same values passed to scrollbars via the-yscrollcommandoption. ๐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 eitherpagesorunits. If what ispagesthen 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 isunits, the view adjusts up or down in units of theyScrollIncrementoption, if it's greater than zero, or in units of one-tenth the window's height otherwise. ๐ซถ
โจ OVERVIEW OF ITEM TYPES โจ
Okay so the sections below describe the various types of items supported by canvas widgets. Each item type is characterized by two things, and bestie you gotta know both: 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. One explanation, forty reuses, that's the efficiency era.
-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 byTk_GetAnchor. For example, if anchorPos iscenterthen the item is centered on the point; if anchorPos isnthen the item will be drawn so that its top center point is at the positioning point. This option defaults tocenter. ๐-dash pattern-activedash pattern-disableddash patternโ these options specify dash patterns for the normal, active state, and disabled state of an item. pattern may have any of the forms accepted byTk_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-dashoption.-dashoffsetis ignored if there is no-dashpattern. 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 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 byTk_GetColor. For thelineitem, it specifies the color of the line drawn. For thetextitem, it specifies the foreground color of the text. If color is an empty string (the default for all canvas items exceptlineandtext), 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 byTk_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 formx,yor side, where side can ben,ne,e,se,s,sw,w,nw, orcenter. 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-offsetoption is used for stippling as well. For thelineandpolygoncanvas items you can also specify an index as argument, which connects the stipple origin to one of the coordinate points of the line/polygon.
Heads up bestie: note that stipple offsets are only supported on X11; they are silently ignored on other platforms. Silently. Not even a little warning. ๐
-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 byTk_GetBitmap. If the-outlineoption 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.
And again: 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-outlineoption controls fill stipples. (See the-outlineoption 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 byTk_GetBitmap. If the-filloption 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 thetextitem, it affects the actual text. And yeah, same warning: 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,disabledorhidden. โจ-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-outlineoption has been specified as an empty string then this option has no effect. This option defaults to1.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 actually meet the item types themselves. the lore. the main characters ๐
๐ ARC ITEMS ๐
Items of type arc show up on your display as arc-shaped regions. an arc is a little slice of an oval, delimited by two angles โ either the ones -start and -extent give you, or the one -height gives you โ and it gets drawn in one of several ways, which is whatever -style says. simple as ๐
Arcs are created with widget commands shaped like this:
pathName create arc x1 y1 x2 y2 ?option value ...?
pathName create arc coordList ?option value ...?
The x1, y1, x2, and y2 args โ or coordList โ give the coords of two diagonally opposite corners of a rectangular region enclosing the oval that defines the arc (except when -height is specified, we'll get to that ๐). After the coordinates you can pile on any number of option-value pairs, each one setting one of the item's config options. and those exact same option-value pairs can be used in itemconfigure widget commands to change the item's configuration, no cap. An arc item becomes the current item whenever 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. yes, even invisible things get to be the current item. representation ๐
The following standard options are supported by arcs:
-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 arcs:
-extentdegrees โ sets the size of the angular range the arc takes up. the arc's range stretches for degrees degrees counter-clockwise from the starting angle that-starthands you. degrees can be negative, live your truth. and if it's greater than 360 or less than -360, then degrees modulo 360 is used as the extent. math but make it fashion โจ-startdegrees โ sets where the angular range occupied by the arc begins. degrees is in units of degrees measured counter-clockwise from the 3-o'clock position, and it can be positive or negative. pick a lane, it supports you ๐ซถ-heightdistance โ the glow-up shortcut for making a circular arc segment: it defines how far the mid-point of the arc sits from its chord. when you use this option, the coordinates get read as the start and end coordinates of the chord, and-startand-extentare just... ignored. not invited to the party. ๐ The value of distance means this:
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
and if you want the 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 ๐ธ
Note that itemcget -height always returns 0, so that introspection code can be kept simple. it's giving "i'm fine" while internally screaming but ok
-styletype โ sets how to draw the arc, and honestly the vibes differ wildly per choice:- if type is
pieslice(the default ๐) then 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 the perimeter section. - if type is
chordthen the arc's region is a section of the oval's perimeter plus a single line segment connecting the two end points of the perimeter section. - if type is
arcthen the arc's region is a section of the perimeter alone. and in this last case the-filloption is ignored. fully ghosted. ๐
- if type is
๐ BITMAP ITEMS ๐
Items of type bitmap appear on the display as images with two colors: foreground and background. two-tone. iconic. very demure.
Bitmaps are created with widget commands shaped like this:
pathName create bitmap x y ?option value ...?
pathName create bitmap coordList ?option value ...?
The x and y args โ or coordList, which must have exactly two elements โ give the coordinates of a point used to position the bitmap on the display, as controlled by the -anchor option. after the coordinates, any number of option-value pairs, each setting a config option for the item. those same option-value pairs also work in itemconfigure widget commands to change the item's configuration. A bitmap item becomes the current item when the mouse pointer is over any part of its bounding box ๐ฆ
The following standard options are supported by bitmaps:
-anchor,-state,-tags
The following extra options are supported for bitmaps:
-backgroundcolor,-activebackgroundcolor,-disabledbackgroundcolor โ these set the color used for each of the bitmap's โ0โ-valued pixels in its normal, active and disabled states. Color may have any of the forms accepted byTk_GetColor. if this option isn't specified, or if it's specified as an empty string, then nothing gets displayed where the bitmap pixels are 0 โ which produces a transparent effect โจ-bitmapbitmap,-activebitmapbitmap,-disabledbitmapbitmap โ these options specify the bitmaps to display in the item in its normal, active and disabled states. Bitmap may have any of the forms accepted byTk_GetBitmap.-foregroundcolor,-activeforegroundcolor,-disabledforegroundcolor โ these specify the color to use for each of the bitmap's โ1โ-valued pixels in its normal, active and disabled states. Color may have any of the forms accepted byTk_GetColor. the glow-up color, if you will ๐
๐ซถ IMAGE ITEMS ๐ซถ
Items of type image are how you put actual images on a canvas. periodt.
Images are created with widget commands shaped like this:
pathName create image x y ?option value ...?
pathName create image coordList ?option value ...?
The x and y args โ or coordList โ give the coordinates of a point used to position the image on the display, as controlled by the -anchor option. after the coordinates, any number of option-value pairs, each setting one of the item's config options. those same option-value pairs work in itemconfigure widget commands to change the item's configuration too. An image item becomes the current item when the mouse pointer is over any part of its bounding box ๐
The following standard options are supported by images:
-anchor,-state,-tags
The following extra options are supported for images:
-imagename,-activeimagename,-disabledimagename โ these specify the name of the images to display in the item in its normal, active and disabled states. and heads up bestie: this image must have been created previously with theimage createcommand. no backdating, no manifesting it into existence ๐
๐ LINE ITEMS ๐
Items of type line appear on the display as one or more connected line segments or curves. and they're fancy, because line items support coordinate indexing operations using the dchars, index and insert widget commands ๐
Lines are created with widget commands shaped like this:
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, any number of option-value pairs, each setting one of the item's config options. and yep, those 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 it's drawn or not, and whether or not the line is smoothed. ghost segments count. we respect them ๐ซก
The following standard options are supported by lines:
-dash,-activedash,-disableddash,-dashoffset,-fill,-activefill,-disabledfill,-stipple,-activestipple,-disabledstipple,-state,-tags,-width,-activewidth,-disabledwidth
The following extra options are supported for lines:
-arrowwhere โ tells you whether arrowheads get drawn at one or both ends of the line. where must be one ofnone(no arrowheads, the default),first(arrowhead at the first point of the line),last(arrowhead at the last point of the line), orboth(arrowheads at both ends, greedy, love that). This option defaults tonone. and here's the tea: when it's asked 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, so the line doesn't extend past the edge of the arrowhead. this may trigger aLeaveevent if the mouse is hovering that line end. conversely, when removing an arrowhead Tk adjusts the corresponding line point the other way round, which may trigger anEnterevent. so like. expect events. it's giving emotional whiplash ๐ญ-arrowshapeshape โ sets 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. the first element gives the distance along the line from the neck of the arrowhead to its tip. the second element gives the distance along the line from the trailing points of the arrowhead to the tip. and the third element gives the distance from the outside edge of the line to the trailing points. if this option isn't specified, Tk just picks a โreasonableโ shape. trust the process โจ-capstylestyle โ specifies the ways caps are drawn at the endpoints of the line. style may have any of the forms accepted byTk_GetCapStyle(butt,projecting, orround). if this option isn't specified then it defaults tobutt. and where arrowheads are drawn, the cap style is ignored. sorry queen, your caps don't get a say there ๐-joinstylestyle โ this is the glow-up for your corners, bestie ๐ it says how the joints get drawn where the line's vertices meet. style can be any of the forms thatTk_GetJoinStyleaccepts, and that means bevel, miter, or round. If you don't say anything, it lowkey defaults toround. And if your line has only two points? This option is literally irrelevant, so don't stress. ๐-smoothsmoothMethod โ the main character option, honestly โจ smoothMethod has to be one of the forms accepted byTcl_GetBooleanor a line smoothing method. In the core onlytrueandraware supported (withbezierbeing an alias fortrue), but more can be added at runtime โ the roster grows, periodt. If you hand it a boolean false value or an empty string, no smoothing is applied. A boolean truth value assumestruesmoothing. If the smoothing method istrue, the line gets drawn as a curve, rendered as a set of quadratic splines: one spline is drawn for the first and second line segments, one for the second and third, and so on. Straight-line segments can be generated within a curve by duplicating the end-points of the desired line segment. If the smoothing method israw, the line also gets drawn as a curve, but the list of coordinates is 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 the cubic Bezier curve. Straight line segments can be generated within a curve by making control points equal to their neighbouring knot points. If the last point is a control point and not a knot point, the point is repeated (one or two times) so that it also becomes a knot point. ๐-splinestepsnumber โ how smooth do you want your curves, diva? ๐ Each spline will be approximated with number line segments. This option is ignored unless the-smoothoption istrueorrawโ so if you skipped smoothing, this one's just sitting there being decorative. ๐
๐ฅ OVAL ITEMS ๐ฅ
Items of type oval show up as circular or oval regions on the display. Each oval may have an outline, a fill, or both โ choose your fighter. ๐ซถ 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 enclosing the oval. The oval will include the top and left edges of the rectangle, not the lower or right edges. If the region is square then the resulting oval is circular; otherwise it is elongated in shape. 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 oval item becomes the current item when the mouse pointer is over any part that is painted or (when fully transparent) that would be painted if both the -fill and -outline options were non-empty. ๐
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. That's the whole menu. ๐
๐ท 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. Polygons are created with widget commands of the following form:
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. The first point should not be repeated as the last to close the shape โ Tk will automatically close the periphery between the first and last points, so don't do the extra work, bestie. ๐
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 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. Iconic behaviour honestly. ๐
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:
-joinstylestyle โ tells you how the joints are drawn at the vertices of the outline. style may have any of the forms accepted byTk_GetJoinStyle(bevel, miter, or round). If this option is not specified then it defaults toround. ๐ซ-smoothboolean โ boolean must have one of the forms accepted byTcl_GetBooleanor a line smoothing method. Onlytrueandraware supported in the core (withbezierbeing an alias fortrue), but more can be added at runtime. If a boolean false value or empty string is given, no smoothing is applied. A boolean truth value assumestruesmoothing. If the smoothing method istrue, the polygon should be drawn as a curve, rendered as a set of quadratic splines: one spline is drawn for the first and second line segments, one for the second and third, and so on. Straight-line segments can be generated within a curve by duplicating the end-points of the desired line segment. If the smoothing method israw, the polygon should also be drawn as a curve, but where the list of coordinates is 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 the cubic Bezier curve. Straight line segments can be generated within a curve by making control points equal to their neighbouring knot points. 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). ๐-splinestepsnumber โ the degree of smoothness desired for curves: each spline will be approximated with number line segments. This option is ignored unless the-smoothoption istrueorraw. โจ
Polygon items are different from other items such as rectangles, ovals and arcs in that interior points are considered to be โinsideโ a polygon (e.g. for purposes of the find closest and find overlapping widget commands) even if it is not filled. For most other item types, an interior point is considered to be inside the item only if the item is filled or if it has neither a fill nor an outline. If you would like an unfilled polygon whose interior points are not considered to be inside the polygon, use a line item instead. That's your workaround, iykyk. ๐
๐ช RECTANGLE ITEMS ๐ช
Items of type rectangle appear as rectangular regions on the display. Each rectangle may have an outline, a fill, or both. Rectangles are created with widget commands of the following form:
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, no more no less) โ give the coordinates of two diagonally opposite corners of the rectangle. The rectangle will include its upper and left edges but not its lower or right edges. 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) that would be painted if both the -fill and -outline options were non-empty. ๐
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. Simple, clean, iconic. ๐ฆ
โจ TEXT ITEMS โจ
Ok bestie, text items are literally just a string of characters chillin' on your canvas, and they can be one line or a whole multi-line moment. ๐
They're full-on interactive too: text items support indexing, editing and selection through these widget commands:
dcharsfocusicursorindexinsertselect
You make one like this:
pathName create text x y ?option value ...?
pathName create text coordList ?option value ...?
So the arguments x and y, or coordList (which must have two elements, no exceptions bestie), specify the coordinates of a point used to position the text on the display โ peep the options below for how the text actually gets displayed. ๐ธ
After the coordinates you can stack any number of option-value pairs, and each one sets a configuration option for the item. Those exact same option-value pairs work in itemconfigure widget commands to change the item's config later. And 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's the extra special sauce โจ โ the following extra options are supported for text items:
-anglerotationDegrees โrotationDegreestells how many degrees to rotate the text anticlockwise about the positioning point for the text. It may have any floating-point value from0.0to360.0. For example, ifrotationDegreesis90, then the text will be drawn vertically from bottom to top. This option defaults to0.0. ๐-fontfontName โ specifies the font to use for the text item.fontNamemay be any string acceptable toTk_GetFont. If this option is not specified, it defaults to a system-dependent font.-justifyhow โ specifies how to justify the text within its bounding region.howmust be one of the valuesleft,right, orcenter. This option will only matter if the text is displayed as multiple lines. If the option is omitted, it defaults toleft.-textstring โstringspecifies the characters to be displayed in the text item. Newline characters cause line breaks. The characters in the item may also be changed with theinsertanddeletewidget commands. This option defaults to an empty string.-underlinenumber โ specifies the integer index of a character within the text to be underlined.0corresponds to the first character of the text displayed,1to the next character, and so on.-1means that no underline should be drawn (if the whole text item is to be underlined, the appropriate font should be used instead). ๐๏ธ-widthlineLength โ 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 thanlineLengthis broken just before a space character to make the line shorter thanlineLength; the space character is treated as if it were a newline character.
๐ช WINDOW ITEMS ๐ช
Items of type window cause a particular window to be displayed at a given position on the canvas. Main character energy, fr fr โ you're literally putting a whole window inside your 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. ๐ iconic behaviour honestly.
The following standard options are supported by window items:
-anchor-state-tags
The following extra options are supported for window items:
-heightpixels โ specifies the height to assign to the item's window.pixelsmay 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.-widthpixels โ specifies the width to assign to the item's window.pixelsmay 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.-windowpathName โ specifies the window to associate with this item. The window specified bypathNamemust either be a child of the canvas widget or a child of some ancestor of the canvas widget.pathNamemay not refer to a top-level window. ๐ซ
โ ๏ธ Heads up bestie, this part is important: note that, 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. ๐
๐ง 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. (Yes bestie, you can go build your own item type from scratch. No cap.)
๐ 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. She's a blank canvas in every sense of the word, literally and thematically. ๐ฆ
๐ 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. Periodt. ๐
๐ SEE ALSO ๐
โญ KEYWORDS โญ
canvas, widget
And that's a wrap on the whole canvas(3tk) page, bestie!! ๐๐ซถ You just read the entire thing, top to bottom, and I'm so proud of you. Go forth and draw some iconic little shapes. ๐
This masterpiece comes to you from Tk version 8.3, dated canvas(3tk) โ mwah, no notes. ๐โจ
๐ฆ where this page comes from
- ubuntu resolute: tk9.0-doc 9.0.3-1
- ubuntu stonking: tk9.0-doc 9.0.4-1
- Copyright (c) 1992-1994 The Regents of the University of California
- Copyright (c) 1994-1996 Sun Microsystems, Inc
- Copyright (c) 1997-1999 Scriptics Corporation
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms