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

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.
主站蜘蛛池模板: 乌兰察布市| 峨眉山市| 华阴市| 桐乡市| 兰溪市| 邳州市| 昌黎县| 墨竹工卡县| 万州区| 黎川县| 永春县| 麻栗坡县| 泰顺县| 祁连县| 塔河县| 万年县| 湖北省| 叙永县| 望奎县| 虹口区| 江城| 岳西县| 大悟县| 灌阳县| 台北市| 赤峰市| 湛江市| 青川县| 东莞市| 思南县| 广饶县| 邵东县| 揭阳市| 临沧市| 尼木县| 临沭县| 安庆市| 兰溪市| 元氏县| 邯郸市| 会东县|