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

(yzsuai) #1

canvas.bind('', self.onClear) # delete all
canvas.bind('', self.onMove) # move latest
self.canvas = canvas
self.drawn = None
self.kinds = [canvas.create_oval, canvas.create_rectangle]


def onStart(self, event):
self.shape = self.kinds[0]
self.kinds = self.kinds[1:] + self.kinds[:1] # start dragout
self.start = event
self.drawn = None


def onGrow(self, event): # delete and redraw
canvas = event.widget
if self.drawn: canvas.delete(self.drawn)
objectId = self.shape(self.start.x, self.start.y, event.x, event.y)
if trace: print(objectId)
self.drawn = objectId


def onClear(self, event):
event.widget.delete('all') # use tag all


def onMove(self, event):
if self.drawn: # move to click spot
if trace: print(self.drawn)
canvas = event.widget
diffX, diffY = (event.x - self.start.x), (event.y - self.start.y)
canvas.move(self.drawn, diffX, diffY)
self.start = event


if name == 'main':
CanvasEventsDemo()
mainloop()


This script intercepts and processes three mouse-controlled actions:


Clearing the canvas
To erase everything on the canvas, the script binds the double left-click event to
run the canvas’s delete method with the all tag—again, a built-in tag that asso-
ciates every object on the screen. Notice that the Canvas widget clicked is available
in the event object passed in to the callback handler (it’s also available as
self.canvas).


Dragging out object shapes
Pressing the left mouse button and dragging (moving it while the button is still
pressed) creates a rectangle or oval shape as you drag. This is often called dragging
out an object—the shape grows and shrinks in an elastic rubber-band fashion as
you drag the mouse and winds up with a final size and location given by the point
where you release the mouse button.
To make this work in tkinter, all you need to do is delete the old shape and draw
another as each drag event fires; both delete and draw operations are fast enough
to achieve the elastic drag-out effect. Of course, to draw a shape to the current


Canvas | 561
Free download pdf