192
Chapter 19. Case study: Tkinter
def __init__(self, item):
self.canvas = item.canvas
self.tag = item.tag
self.bind('', self.select)
self.bind('', self.drag)
self.bind('', self.drop)
The init method takes an Item as a parameter. It copies the attributes of the Item and then creates
bindings for three events: a button press, button motion, and button release.
The event handler select stores the coordinates of the current event and the original color of the
item, then changes the color to yellow:
def select(self, event):
self.dragx = event.x
self.dragy = event.y
self.fill = self.cget('fill')
self.config(fill='yellow')
cget
stands for “get configuration;” it takes the name of an option as a string and returns the current
value of that option.
drag
computes how far the object has moved relative to the starting place, updates the stored coor-
dinates, and then moves the item.
def drag(self, event):
dx = event.x - self.dragx
dy = event.y - self.dragy
self.dragx = event.x
self.dragy = event.y
self.move(dx, dy)
This computation is done in pixel coordinates; there is no need to convert to Canvas coordinates.
Finally, drop restores the original color of the item:
def drop(self, event):
self.config(fill=self.fill)
You can use the Draggable class to add drag-and-drop capability to an existing item. For example,
here is a modified version of make_circle that uses circle to create an Item and Draggable to
make it draggable:
def make_circle(event):
pos = ca.canvas_coords([event.x, event.y])
item = ca.circle(pos, 5, fill='red')
item = Draggable(item)
This example demonstrates one of the benefits of inheritance: you can modify the capabilities of
a parent class without modifying its definition. This is particularly useful if you want to change
behavior defined in a module you did not write.
Do'stlaringiz bilan baham: |