pythonware.com | products ::: library ::: search ::: daily Python-URL! |
Events and BindingsChapter 7. Events and BindingsAs was mentioned earlier, a Tkinter application spends most of its time inside an event loop (entered via the mainloop method). Events can come from various sources, including key presses and mouse operations by the user, and redraw events from the window manager (indirectly caused by the user, in many cases). Tkinter provides a powerful mechanism to let you deal with events yourself. For each widget, you can bind Python functions and methods to events. widget.bind(event, handler) If an event matching the event description occurs in the widget, the given handler is called with an object describing the event. Here's a simple example: Example 7-1. Capturing clicks in a window # File: bind1.py from Tkinter import * root = Tk() def callback(event): print "clicked at", event.x, event.y frame = Frame(root, width=100, height=100) frame.bind("<Button-1>", callback) frame.pack() root.mainloop() In this example, we use the bind method of the frame widget to bind a callback function to an event called <Button-1>. Run this program and click in the window that appears. Each time you click, a message like "clicked at 44 63" is printed to the console window. EventsEvents are given as strings, using a special event syntax: <modifier-type-detail> The type field is the most important part of an event specifier. It specifies the kind of event that we wish to bind, and can be user actions like Button, and Key, or window manager events like Enter, Configure, and others. The modifier and detail fields are used to give additional information, and can in many cases be left out. There are also various ways to simplify the event string; for example, to match a keyboard key, you can leave out the angle brackets and just use the key as is. Unless it is a space or an angle bracket, of course. Instead of spending a few pages on discussing all the syntactic shortcuts, let's take a look on the most common event formats: Table 7-1. Event Formats
The Event ObjectThe event object is a standard Python object instance, with a number of attributes describing the event. Table 7-2. Event Attributes
For portability reasons, you should stick to char, height, width, x, y, x_root, y_root, and widget unless you know exactly what you're doing... Instance and Class BindingsThe bind method we used in the above example creates an instance binding. This means that the binding applies to a single widget only; if you create new frames, they will not inherit the bindings. But Tkinter also allows you to create bindings on the class and application level; in fact, you can create bindings on four different levels:
For example, you can use bind_all to create a binding for the F1 key, so you can provide help everywhere in the application. But what happens if you create multiple bindings for the same key, or provide overlapping bindings? First, on each of these four levels, Tkinter chooses the "closest match" of the available bindings. For example, if you create instance bindings for the <Key> and <Return> events, only the second binding will be called if you press the Enter key. However, if you add a <Return> binding to the toplevel widget, both bindings will be called. Tkinter first calls the best binding on the instance level, then the best binding on the toplevel window level, then the best binding on the class level (which is often a standard binding), and finally the best available binding on the application level. So in an extreme case, a single event may call four event handlers. A common cause of confusion is when you try to use bindings to override the default behavior of a standard widget. For example, assume you wish to disable the Enter key in the text widget, so that the users cannot insert newlines into the text. Maybe the following will do the trick? def ignore(event): pass text.bind("<Return>", ignore) or, if you prefer one-liners: text.bind("<Return>", lambda e: None) (the lambda function used here takes one argument, and returns None) Unfortunately, the newline is still inserted, since the above binding applies to the instance level only, and the standard behavior is provided by a class level bindings. You could use the bind_class method to modify the bindings on the class level, but that would change the behavior of all text widgets in the application. An easier solution is to prevent Tkinter from propagating the event to other handlers; just return the string "break" from your event handler: def ignore(event): return "break" text.bind("<Return>", ignore) or text.bind("<Return>", lambda e: "break") By the way, if you really want to change the behavior of all text widgets in your application, here's how to use the bind_class method: top.bind_class("Text", "<Return>", lambda e: None) But there are a lot of reasons why you shouldn't do this. For example, it messes things up completely the day you wish to extend your application with some cool little UI component you downloaded from the net. Better use your own Text widget specialization, and keep Tkinter's default bindings intact: class MyText(Text): def __init__(self, master, **kw): apply(Text.__init__, (self, master), kw) self.bind("<Return>", lambda e: "break") ProtocolsIn addition to event bindings, Tkinter also supports a mechanism called protocol handlers. Here, the term protocol refers to the interaction between the application and the window manager. The most commonly used protocol is called WM_DELETE_WINDOW, and is used to define what happens when the user explicitly closes a window using the window manager. You can use the protocol method to install a handler for this protocol (the widget must be a root or Toplevel widget): widget.protocol("WM_DELETE_WINDOW", handler) Once you have installed your own handler, Tkinter will no longer automatically close the window. Instead, you could for example display a message box asking the user if the current data should be saved, or in some cases, simply ignore the request. To close the window from this handler, simply call the destroy method of the window: Example 7-2. Capturing destroy events # File: protocol1.py from Tkinter import * import tkMessageBox def callback(): if tkMessageBox.askokcancel("Quit", "Do you really wish to quit?"): root.destroy() root = Tk() root.protocol("WM_DELETE_WINDOW", callback) root.mainloop() Note that even you don't register an handler for WM_DELETE_WINDOW on a toplevel window, the window itself will be destroyed as usual (in a controlled fashion, unlike X). However, as of Python 1.5.2, Tkinter will not destroy the corresponding widget instance hierarchy, so it is a good idea to always register a handler yourself: top = Toplevel(...) # make sure widget instances are deleted top.protocol("WM_DELETE_WINDOW", top.destroy) Future versions of Tkinter will most likely do this by default. Other ProtocolsWindow manager protocols were originally part of the X window system (they are defined in a document titled Inter-Client Communication Conventions Manual, or ICCCM). On that platform, you can install handlers for other protocols as well, like WM_TAKE_FOCUS and WM_SAVE_YOURSELF. See the ICCCM documentation for details. |