image.png
""" draw elastic shapes on a canvas on drag, move on right click; see canvasDraw_tags*.py for extensions with tags and animation """
from tkinter import * trace = False
class CanvasEventsDemo: def init(self, parent=None): canvas = Canvas(width=300, height=300, bg='beige') canvas.pack() canvas.bind('<ButtonPress-1>', self.onStart) # click canvas.bind('<B1-Motion>', self.onGrow) # and drag canvas.bind('<Double-1>', self.onClear) # delete all canvas.bind('<ButtonPress-3>', self.onMove) # move latest self.canvas = canvas self.drawn = None self.kinds = [canvas.create_oval, canvas.create_rectangle]
代码语言:javascript复制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()
bind events on both canvas and its items
from tkinter import *
def onCanvasClick(event): print('Got canvas click', event.x, event.y, event.widget)
def onObjectClick(event): print('Got object click', event.x, event.y, event.widget, end=' ') print(event.widget.find_closest(event.x, event.y)) # find text object's ID
root = Tk() canv = Canvas(root, width=100, height=100) obj1 = canv.create_text(50, 30, text='Click me one') obj2 = canv.create_text(50, 70, text='Click me two')
canv.bind('<Double-1>', onCanvasClick) # bind to whole canvas canv.tag_bind(obj1, '<Double-1>', onObjectClick) # bind to drawn item canv.tag_bind(obj2, '<Double-1>', onObjectClick) # a tag works here too canv.pack() root.mainloop()