The Canvas Widget

Class Canvas is a powerful, flexible widget used for many purposes, including plotting and, in particular, building custom widgets. Building custom widgets is an advanced topic, and I do not cover it further in this book. This section covers only a subset of Canvas functionality used for the simplest kind of plotting.

Coordinates within a Canvas instance c are in pixels, with origin at the upper-left corner of c, and positive coordinates growing rightward and down. Some advanced methods let you change c’s coordinate system, but I do not cover them in this book.

What you draw on a Canvas instance c are canvas items: lines, polygons, Tkinter images, arcs, ovals, texts, and others. Each item has an item handle by which you can refer to the item. You can also assign symbolic names called tags to sets of canvas items (the sets of items with different tags can overlap). ALL is a predefined tag that applies to all items; CURRENT is a predefined tag that applies to the item under the mouse pointer.

Tags on a Canvas are different from tags on a Text. Canvas tags are nothing more than sets of items, with no independent existence. When you perform any operation with a Canvas tag as the item identifier, the operation occurs on the items that are in the tag’s current set. It makes no difference if items are later removed from or added to that tag.

To create a canvas item, call on c a method with a name of the form create_kindofitem, which returns the new item’s handle. Methods ...

Get Python in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.