Object identifiers and operations
Although not used by the canvas1 script, every object you put on a canvas has an iden-
tifier, returned by the create_ method that draws or embeds the object (what was coded
as id in the last section’s examples). This identifier can later be passed to other methods
that move the object to new coordinates, set its configuration options, delete it from
the canvas, raise or lower it among other overlapping objects, and so on.
For instance, the canvas move method accepts both an object identifier and X and Y
offsets (not coordinates), and it moves the named object by the offsets given:
canvas.move(objectIdOrTag, offsetX, offsetY) # move object(s) by offset
If this happens to move the object off-screen, it is simply clipped (not shown). Other
common canvas operations process objects, too:
canvas.delete(objectIdOrTag) # delete object(s) from canvas
canvas.tkraise(objectIdOrTag) # raise object(s) to front
canvas.lower(objectIdOrTag) # lower object(s) below others
canvas.itemconfig(objectIdOrTag, fill='red') # fill object(s) with red color
Notice the tkraise name—raise by itself is a reserved word in Python. Also note that
the itemconfig method is used to configure objects drawn on a canvas after they have
been created; use config to set configuration options for the canvas itself. Probably the
best thing to notice here, though, is that because tkinter is based on structured objects,
you can process a graphic object all at once; there is no need to erase and redraw each
pixel manually to implement a move or a raise.
Canvas object tags
But canvases offer even more power than suggested so far. In addition to object iden-
tifiers, you can also perform canvas operations on entire sets of objects at once, by
associating them all with a tag, a name that you make up and apply to objects on the
display. Tagging objects in a Canvas is at least similar in spirit to tagging substrings in
the Text widget we studied in the prior section. In general terms, canvas operation
methods accept either a single object’s identifier or a tag name.
For example, you can move an entire set of drawn objects by associating all with the
same tag and passing the tag name to the canvas move method. In fact, this is why
move takes offsets, not coordinates—when given a tag, each object associated with the
tag is moved by the same (X,Y) offsets; absolute coordinates would make all the tagged
objects appear on top of each other instead.
To associate an object with a tag, either specify the tag name in the object drawing call’s
tag option or call the addtag_withtag(tag, objectIdOrTag) canvas method (or its rel-
atives). For instance:
canvas.create_oval(x1, y1, x2, y2, fill='red', tag='bubbles')
canvas.create_oval(x3, y3, x4, y4, fill='red', tag='bubbles')
objectId = canvas.create_oval(x5, y5, x6, y6, fill='red')
Canvas | 553