self.canvas.master.bind('
self.kinds = self.create_oval_tagged, self.create_rectangle_tagged
def create_oval_tagged(self, x1, y1, x2, y2):
objectId = self.canvas.create_oval(x1, y1, x2, y2)
self.canvas.itemconfig(objectId, tag='ovals', fill='blue')
return objectId
def create_rectangle_tagged(self, x1, y1, x2, y2):
objectId = self.canvas.create_rectangle(x1, y1, x2, y2)
self.canvas.itemconfig(objectId, tag='rectangles', fill='red')
return objectId
def onMoveOvals(self, event):
print('moving ovals')
self.moveInSquares(tag='ovals') # move all tagged ovals
def onMoveRectangles(self, event):
print('moving rectangles')
self.moveInSquares(tag='rectangles')
def moveInSquares(self, tag): # 5 reps of 4 times per sec
for i in range(5):
for (diffx, diffy) in [(+20, 0), (0, +20), (−20, 0), (0, −20)]:
self.canvas.move(tag, diffx, diffy)
self.canvas.update() # force screen redraw/update
time.sleep(0.25) # pause, but don't block GUI
if name == 'main':
CanvasEventsDemo()
mainloop()
All three of the scripts in this section create a window of blue ovals and red rectangles
as you drag new shapes out with the left mouse button. The drag-out implementation
itself is inherited from the superclass. A right-mouse-button click still moves a single
shape immediately, and a double-left click still clears the canvas, too—other operations
inherited from the original superclass. In fact, all this new script really does is change
the object creation calls to add tags and colors to drawn objects here, add a text field
at the top of the canvas, and add bindings and callbacks for motion requests. Fig-
ure 9-42 shows what this subclass’s window looks like after dragging out a few shapes
to be animated.
The “o” and “r” keys are set up to start animation of all the ovals and rectangles you’ve
drawn, respectively. Pressing “o,” for example, makes all the blue ovals start moving
synchronously. Objects are animated to mark out five squares around their location
and to move four times per second. New objects drawn while others are in motion start
to move, too, because they are tagged. You need to run these live to get a feel for the
simple animations they implement, of course. (You could try moving this book back
and forth and up and down, but it’s not quite the same, and might look silly in public
places.)
590 | Chapter 9: A tkinter Tour, Part 2