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

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.
主站蜘蛛池模板: 林甸县| 遵化市| 凤冈县| 新和县| 江阴市| 土默特右旗| 二连浩特市| 元氏县| 大荔县| 龙泉市| 开远市| 茂名市| 泰兴市| 凤庆县| 马龙县| 宁远县| 马公市| 昌江| 泰州市| 历史| 固原市| 大石桥市| 景泰县| 山阳县| 叙永县| 自贡市| 罗山县| 商水县| 中超| 紫金县| 长子县| 日喀则市| 霍邱县| 正镶白旗| 仲巴县| 集贤县| 康马县| 成武县| 军事| 东山县| 孟津县|