fromTkinterImport*Importthreading, Timetrace=0classCanvaseventsdemo:def __init__(Self, parent=None): Canvas= Canvas (width=300, height=300, bg='Beige') Canvas.pack () Canvas.bind ('<ButtonPress-1>', Self.onstart)#ClickCanvas.bind ('<B1-Motion>', Self.ongrow)#and DragCanvas.bind ('<Double-1>', Self.onclear)#Delete AllCanvas.bind ('<ButtonPress-3>', Self.onmove)#Move LatestSelf.canvas =Canvas Self.drawn=None self.kinds=[Canvas.create_oval, Canvas.create_rectangle]defOnStart (Self, event): Self.shape=Self.kinds[0] Self.kinds= self.kinds[1:] + self.kinds[:1]#Start DragoutSelf.start =Event Self.drawn=NonedefOngrow (self, event):#Delete and RedrawCanvas =Event.widgetifSelf.drawn:canvas.delete (self.drawn) objectId=Self.shape (Self.start.x, Self.start.y, Event.x, Event.y)ifTracePrint(objectId) Self.drawn=objectIddefonclear (Self, event): Event.widget.delete (' All')#Use tag all defOnMove (Self, event):ifSelf.drawn:#move to click Spot ifTracePrint(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=Eventclasscanvaseventsdemotags (Canvaseventsdemo):def __init__(Self, parent=None): Canvaseventsdemo.__init__(self, parent) Self.canvas.create_text (text=, 8,'Press O and R to move shapes') Self.canvas.master.bind ('<KeyPress-o>', Self.onmoveovals) Self.canvas.master.bind ('<KeyPress-r>', self.onmoverectangles) self.kinds=self.create_oval_tagged, self.create_rectangle_taggeddefcreate_oval_tagged (self, x1, y1, x2, y2): ObjectId=self.canvas.create_oval (x1, y1, x2, y2) self.canvas.itemconfig (objectId, Tag='Ovals', fill='Blue') returnobjectIddefcreate_rectangle_tagged (self, x1, y1, x2, y2): ObjectId=self.canvas.create_rectangle (x1, y1, x2, y2) self.canvas.itemconfig (objectId, Tag='rectangles', fill='Red') returnobjectIddefonmoveovals (Self, event):Print('Moving Ovals') self.moveinsquares (tag='Ovals')#move all tagged ovals defonmoverectangles (Self, event):Print('Moving rectangles') self.moveinsquares (tag='rectangles') defMoveinsquares (self, Tag):#5 reps of 4 times per sec forIinchRange (5): for(DIFFX, Diffy)inch[(+20, 0), (0, +20), (-20, 0), (0,-20))]: Self.canvas.move (tag, DIFFX, Diffy) self.canvas.update ()#Force screen Redraw/updateTime.sleep (0.25)#pause, but don ' t block GUIclassCanvaseventsdemothread (canvaseventsdemotags):defMoveem (self, tag): forIinchRange (5): for(DIFFX, Diffy)inch[(+20, 0), (0, +20), (-20, 0), (0,-20))]: Self.canvas.move (tag, DIFFX, Diffy) time.sleep (0.25)#Pause this thread is only defmoveinsquares (self, Tag): Threading. Thread (Self.moveem, (tag,)). Start ()if __name__=='__main__': Canvaseventsdemothread () Mainloop ()
Tkinter Event Advanced Usage Example