"""
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('
canvas.bind('
canvas.bind('
canvas.bind('
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()
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('
canv.tag_bind(obj1, '
canv.tag_bind(obj2, '
canv.pack()
root.mainloop()