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

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().

主站蜘蛛池模板: 大方县| 宜宾县| 文山县| 木兰县| 麟游县| 香港 | 高邑县| 昌邑市| 岱山县| 永修县| 松潘县| 威海市| 信丰县| 固始县| 汝城县| 泾阳县| 凌云县| 丹江口市| 望谟县| 富源县| 海兴县| 新建县| 济源市| 上栗县| 安阳县| 资源县| 陇川县| 石家庄市| 黔南| 崇阳县| 兴义市| 措勤县| 博罗县| 黄梅县| 方正县| 潍坊市| 科技| 建瓯市| 山阴县| 西丰县| 凤凰县|