- Tkinter GUI Application Development Blueprints(Second Edition)
- Bhaskar Chaudhary
- 390字
- 2021-06-24 18:35:05
Event binding
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.
- Vue.js 3.0源碼解析(微課視頻版)
- HTML5+CSS3網站設計教程
- 琢石成器:Windows環(huán)境下32位匯編語言程序設計
- BIM概論及Revit精講
- Protocol-Oriented Programming with Swift
- Mobile Device Exploitation Cookbook
- C/C++數據結構與算法速學速用大辭典
- 深入理解C指針
- 計算機應用基礎教程(Windows 7+Office 2010)
- Learning Nessus for Penetration Testing
- H5+移動營銷設計寶典
- 黑莓(BlackBerry)開發(fā)從入門到精通
- SEO教程:搜索引擎優(yōu)化入門與進階(第3版)
- Python深度學習與項目實戰(zhàn)
- Opa Application Development