Fortunately, Tkinter provides an alternative event binding mechanism called bind() to let you deal with different events. The standard syntax used to bind an event is as follows:
widget.bind(event, handler, add=None)
When an event corresponding to the event description occurs in the widget, it calls not only the associated handler, which passes an instance of the event object as the argument, but also the details of the event. If there already exists a binding for that event for this widget, the old callback is usually replaced with the new handler, but you can trigger both the callbacks by passing add='+' as the last argument.
Let's look at an example of the bind() method (code 1.09.py):
import tkinter as tk
root = tk.Tk()
tk.Label(root, text='Click at different\n locations in the frame below').pack()
def callback(event):
print(dir(event))
print("you clicked at", event.x, event.y)
frame = tk.Frame(root, bg='khaki', width=130, height=80)
frame.bind("<Button-1>", callback)
frame.pack()
root.mainloop()
The following is a description of the preceding code:
- We bind the Frame widget to the <Button-1> event, which corresponds to the left-click. When this event occurs, it calls the callback function, passing an object instance as its argument.
- We define the callback(event) function. Note that it takes the event object generated by the event as an argument.
- We inspect the event object by using dir(event), which returns a sorted list of attribute names for the event object passed to it. This prints the following list:
[ '__doc__' , '__module__' , 'char' , 'delta' , 'height' , 'keycode' , 'keysym' , keysym_num' , 'num' , 'send_event' , 'serial' , 'state' ,'time' , 'type' , 'widget' , 'width' , 'x' , 'x_root' , 'y' , 'y_root ']
- From the attributes list generated by the object, we use two attributes, event.x and event.y, to print the coordinates of the point of click.
When you run the preceding code (code 1.09.py ), it produces a window, as shown in the following screenshot:
When you left-click anywhere in the yellow colored frame within the root window, it outputs messages to the console. A sample message passed to the console is as follows:
['__doc__', '__module__', 'char', 'delta', 'height', 'keycode', 'keysym', 'keysym_num', 'num', 'send_event', 'serial', 'state', 'time', 'type', 'widget', 'width', 'x', 'x_root', 'y', 'y_root']
You clicked at 63 36.