12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

190 Chapter 19. Casestudy: Tkinterdef __init__(self, item):self.canvas = item.canvasself.tag = item.tagself.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 createsbindings for threeevents: abutton press,button motion, and button release.The event handler select stores the coordinates of the current event and the original color of theitem, then changes thecolor toyellow:def select(self, event):self.dragx = event.xself.dragy = event.yself.fill = self.cget('fill')self.config(fill='yellow')cgetstandsfor“getconfiguration;”ittakesthenameofanoptionasastringandreturnsthecurrentvalue of that option.drag computes how far the object has moved relative to the starting place, updates the stored coordinates,and then moves the item.def drag(self, event):dx = event.x - self.dragxdy = event.y - self.dragyself.dragx = event.xself.dragy = event.yself.move(dx, dy)This computation isdone inpixel coordinates; thereisno need toconvert toCanvas coordinates.Finally,droprestorestheoriginal color of the item:def drop(self, event):self.config(fill=self.fill)You can use theDraggable 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 tomake 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 ofa parent class without modifying its definition. This is particularly useful if you want to changebehavior defined inamodule you did not write.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!