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

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.
主站蜘蛛池模板: 克东县| 曲靖市| 美姑县| 鸡西市| 岐山县| 淮滨县| 金溪县| 和顺县| 彝良县| 南澳县| 兖州市| 安新县| 图木舒克市| 景德镇市| 朝阳区| 山东省| 邵阳市| 麻阳| 花莲市| 灌云县| 马山县| 镇雄县| 漠河县| 三明市| 岳普湖县| 盘锦市| 吉水县| 桑植县| 关岭| 新密市| 耒阳市| 湖北省| 乃东县| 庆阳市| 长岛县| 资溪县| 安陆市| 南雄市| 长乐市| 濉溪县| 洪洞县|