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

Event patterns

In the previous example, you learned how to use the <Button-1> event to denote a left-click. This is a built-in pattern in Tkinter that maps it to a left-click event. Tkinter has an exhaustive mapping scheme that perfectly identifies events such as this one.

Here are some examples to give you an idea of event patterns:

In general, the mapping pattern takes the following form:

<[event modifier-]...event type [-event detail]>

Typically, an event pattern will comprise the following:

  • An event type: Some common event types include Button, ButtonReleaseKeyRelease, Keypress, FocusIn, FocusOut, Leave (when the mouse leaves the widget), and MouseWheel. For a complete list of event types, refer to the event types section at http://www.tcl.tk/man/tcl8.6/TkCmd/bind.htm#M7
  • An event modifier (optional): Some common event modifiers include AltAny (used like <Any-KeyPress>), Control, Double (used like <Double-Button-1> to denote a double-click of the left mouse button), Lock, and Shift. For a complete list of event modifiers, refer to the event modifiers section at http://www.tcl.tk/man/tcl8.6/TkCmd/bind.htm#M6.
  • The event detail (optional): The mouse event detail is captured by the number 1 for a left-click and the number 2 for a right-click. Similarly, each key press on the keyboard is either represented by the key letter itself (say, B in <KeyPress-B>) or by using a key symbol abbreviated as keysym. For example, the up arrow key on the keyboard is represented by the keysym value of KP_Up. For a complete keysym mapping, refer to https://www.tcl.tk/man/tcl8.6/TkCmd/bind.htm.

Let's take a look at a practical example of event binding on widgets (refer to code 1.10.py for the complete working example):

The following is a modified snippet of code; it will give you an idea of commonly
used event bindings:

widget.bind("<Button-1>", callback) #bind widget to left mouse click
widget.bind("<Button-2>", callback) # bind to right mouse click
widget.bind("<Return>", callback)# bind to Return(Enter) Key
widget.bind("<FocusIn>", callback) #bind to Focus in Event
widget.bind("<KeyPress-A>", callback)# bind to keypress A
widget.bind("<KeyPress-Caps_Lock>", callback)# bind to CapsLock keysym
widget.bind("<KeyPress-F1>", callback)# bind widget to F1 keysym
widget.bind("<KeyPress-KP_5>", callback)# bind to keypad number 5
widget.bind("<Motion>", callback) # bind to motion over widget
widget.bind("<Any-KeyPress>", callback) # bind to any keypress

Rather than binding an event to a particular widget, you can also bind it to the top-level window. The syntax remains the same except that now you call it on the root instance of the root window such as root.bind().

主站蜘蛛池模板: 平顶山市| 杭锦后旗| 盖州市| 新余市| 尼勒克县| 南岸区| 乌鲁木齐市| 嵊州市| 高邮市| 洮南市| 论坛| 洪江市| 宜城市| 乌恰县| 霍城县| 凤城市| 伊川县| 嘉善县| 北流市| 宁晋县| 莱芜市| 元朗区| 江都市| 邵东县| 镇雄县| 东光县| 顺昌县| 马尔康县| 绍兴市| 新蔡县| 宝鸡市| 磐安县| 婺源县| 宁化县| 金平| 武威市| 克拉玛依市| 车致| 朔州市| 新竹市| 同心县|