Binding events on specific items
Much like we did for the Text widget, it is also possible to bind events for one or more
specific objects drawn on a Canvas with its tag_bind method. This call accepts either a
tag name string or an object ID in its first argument. For instance, you can register a
different callback handler for mouse clicks on every drawn item or on any in a group
of drawn and tagged items, rather than for the entire canvas at large. Example 9-17
binds a double-click handler on both the canvas itself and on two specific text items
within it, to illustrate the interfaces. It generates Figure 9-28 when run.
Example 9-17. PP4E\Gui\Tour\canvas-bind.py
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()
Figure 9-28. Canvas-bind window
Object IDs are passed to tag_bind here, but a tag name string would work too, and
would allow you to associate multiple canvas objects as a group for event purposes.
When you click outside the text items in this script’s window, the canvas event handler
fires; when either text item is clicked, both the canvas and the text object handlers fire.
Here is the stdout result after clicking on the canvas twice and on each text item once;
Canvas | 563