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

Binding levels

In the previous section, you had a look at how to bind an event to an instance of a widget. This can be called an instance-level binding.

However, there may be times when you need to bind events to an entire application. At times, you may want to bind an event to a particular class of widget. Tkinter provides the following levels of binding options for this:

  • Application-level binding: Application-level bindings let you use the same binding across all windows and widgets of an application as long as any one window of the application is in focus. The syntax for application-level bindings is as follows:
widget.bind_all(event, callback, add=None)

The typical usage pattern is as follows:

root.bind_all('<F1>', show_help)

Application-level binding here means that, irrespective of the widget that is currently under focus, pressing the F1 key will always trigger the show_help callback as long as the application is in focus.

  • Class-level binding: You can also bind events at a particular class level. This is normally used to set the same behavior for all instances of a particular widget class. The syntax for class-level binding is as follows:
w.bind_class(class_name, event, callback, add=None)

The typical usage pattern is as follows:

my_entry.bind_class('Entry', '<Control-V>', paste)

In the preceding example, all the entry widgets will be bound to the <Control-V> event, which will call a method named paste (event).

Event propagation
Most keyboard and mouse events occur at the operating system level. The event propagates hierarchically upward from its source until it finds a window that has the corresponding binding. The event propagation does not stop there. It propagates itself upwards, looking for other bindings from other widgets, until it reaches the root window. If it does reach the root window and no bindings are discovered by it, the event is disregarded.
主站蜘蛛池模板: 措勤县| 永寿县| 革吉县| 德阳市| 苍南县| 武义县| 浦县| 射洪县| 崇阳县| 武汉市| 武平县| 巴彦淖尔市| 渝北区| 石门县| 苍梧县| 游戏| 彰武县| 清河县| 洛南县| 鹤峰县| 大港区| 团风县| 手游| 泌阳县| 康平县| 拉孜县| 阜宁县| 洛川县| 永春县| 维西| 湖口县| 手游| 故城县| 临汾市| 苍南县| 惠水县| 伊宁市| 平度市| 孟津县| 建昌县| 河间市|