[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1
canvas.addtag_withtag('bubbles', objectId)
canvas.move('bubbles', diffx, diffy)

This makes three ovals and moves them at the same time by associating them all with
the same tag name. Many objects can have the same tag, many tags can refer to the
same object, and each tag can be individually configured and processed.


As in Text, Canvas widgets have predefined tag names too: the tag all refers to all objects
on the canvas, and current refers to whatever object is under the mouse cursor. Besides
asking for an object under the mouse, you can also search for objects with the find_
canvas methods: canvas.find_closest(X,Y), for instance, returns a tuple whose first
item is the identifier of the closest object to the supplied coordinates—handy after
you’ve received coordinates in a general mouse-click event callback.


We’ll revisit the notion of canvas tags by example later in this chapter (see the animation
scripts near the end if you need more details right away). As usual, canvases support
additional operations and options that we don’t have space to cover in a finite text like
this (e.g., the canvas postscript method lets you save the canvas in a PostScript file).
See later examples in this book, such as PyDraw, for more details, and consult other
Tk or tkinter references for an exhaustive list of canvas object options.


Scrolling Canvases


One canvas-related operation is so common, though, that it does merit a look here. As
demonstrated in Example 9-14, scroll bars can be cross-linked with a canvas using the
same protocols we used to add them to listboxes and text earlier, but with a few unique
requirements.


Example 9-14. PP4E\Gui\Tour\scrolledcanvas.py


"a simple vertically-scrollable canvas component and demo"


from tkinter import *


class ScrolledCanvas(Frame):
def init(self, parent=None, color='brown'):
Frame.init(self, parent)
self.pack(expand=YES, fill=BOTH) # make me expandable
canv = Canvas(self, bg=color, relief=SUNKEN)
canv.config(width=300, height=200) # display area size
canv.config(scrollregion=(0, 0, 300, 1000)) # canvas size corners
canv.config(highlightthickness=0) # no pixels to border


sbar = Scrollbar(self)
sbar.config(command=canv.yview) # xlink sbar and canv
canv.config(yscrollcommand=sbar.set) # move one moves other
sbar.pack(side=RIGHT, fill=Y) # pack first=clip last
canv.pack(side=LEFT, expand=YES, fill=BOTH) # canv clipped first


self.fillContent(canv)
canv.bind('', self.onDoubleClick) # set event handler


554 | Chapter 9: A tkinter Tour, Part 2

Free download pdf