Next / Previous / Contents / Shipman's homepage

54. Events: responding to stimuli

An event is something that happens to your application—for example, the user presses a key or clicks or drags the mouse—to which the application needs to react.

The widgets normally have a lot of built-in behaviors. For example, a button will react to a mouse click by calling its command callback. For another example, if you move the focus to an entry widget and press a letter, that letter gets added to the content of the widget.

However, the event binding capability of Tkinter allows you to add, change, or delete behaviors.

First, some definitions:

54.1. Levels of binding

You can bind a handler to an event at any of three levels:

  1. Instance binding: You can bind an event to one specific widget. For example, you might bind the PageUp key in a canvas widget to a handler that makes the canvas scroll up one page. To bind an event of a widget, call the .bind() method on that widget (see Section 26, “Universal widget methods”).

    For example, suppose you have a canvas widget named self.canv and you want to draw an orange blob on the canvas whenever the user clicks the mouse button 2 (the middle button). To implement this behavior:

        self.canv.bind('<Button-2>', self.__drawOrangeBlob)

    The first argument is a sequence descriptor that tells Tkinter that whenever the middle mouse button goes down, it is to call the event handler named self.__drawOrangeBlob. (See Section 54.6, “Writing your handler: The Event class”, below, for an overview of how to write handlers such as .__drawOrangeBlob()). Note that you omit the parentheses after the handler name, so that Python will pass in a reference the handler instead of trying to call it right away.

  2. Class binding: You can bind an event to all widgets of a class. For example, you might set up all Button widgets to respond to middle mouse button clicks by changing back and forth between English and Japanese labels. To bind an event to all widgets of a class, call the .bind_class() method on any widget (see Section 26, “Universal widget methods”, above).

    For example, suppose you have several canvases, and you want to set up mouse button 2 to draw an orange blob in any of them. Rather than having to call .bind() for every one of them, you can set them all up with one call something like this:

        self.bind_class('Canvas', '<Button-2>',
  3. Application binding: You can set up a binding so that a certain event calls a handler no matter what widget has the focus or is under the mouse. For example, you might bind the PrintScrn key to all the widgets of an application, so that it prints the screen no matter what widget gets that key. To bind an event at the application level, call the .bind_all() method on any widget (see Section 26, “Universal widget methods”).

    Here's how you might bind the PrintScrn key, whose “key name” is 'Print':

        self.bind_all('<Key-Print>', self.__printScreen)