官术网_书友最值得收藏!

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.
主站蜘蛛池模板: 九龙城区| 桐梓县| 安塞县| 慈利县| 六枝特区| 阿坝| 固原市| 平乡县| 镇安县| 九寨沟县| 福海县| 平安县| 江北区| 漾濞| 衡东县| 阳泉市| 文化| 泸水县| 沅江市| 张家界市| 鹤岗市| 沾益县| 汽车| 武夷山市| 日土县| 岱山县| 宾阳县| 邢台县| 佳木斯市| 墨脱县| 循化| 汝阳县| 平罗县| 高清| 大新县| 云梦县| 托里县| 陵川县| 关岭| 子洲县| 黄陵县|