12.07.2015 Views

Tkinter reference: A GUI for Python

Tkinter reference: A GUI for Python

Tkinter reference: A GUI for Python

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

22.1 Levels of bindingYou 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, youmight bind the PAGEUP key in a canvas widget to a handler that makes the canvasscroll up one page. To bind an event of a widget, call the .bind() method on thatwidget (see Universal methods, above).For example, suppose you have a canvas widget named self.canv and you wantto 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 ( "", self.__drawOrangeBlob )The first argument is a sequence descriptor that tells <strong>Tkinter</strong> that wheneverthe middle mouse button goes down, it is to call the event handler namedself.__drawOrangeBlob. (See the section Writing an event handler, below, <strong>for</strong>an overview of how to write handlers such as .__drawOrangeBlob()). Note thatyou omit the parentheses after the handler name, so that <strong>Python</strong> will pass in a<strong>reference</strong> 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, youmight set up all Button widgets to respond to middle mouse button clicks bychanging back and <strong>for</strong>th between English and Japanese labels. To bind an event toall widgets of a class, call the .bind_class() method on any widget (see Universalmethods, above).For example, suppose you have several canvases, and you want to set up mousebutton 2 to draw an orange blob in any of them. Rather than having to call .bind()<strong>for</strong> every one of them, you can set them all up with one call something like:self.bind_class ( "Canvas", "",self.__drawOrangeBlob )3. Application binding: You can set up a binding so that a certain event calls a handlerno matter what widget has the focus or is under the mouse. For example, you mightbind the PRINTSCRN key to all the widgets of an application, so that it prints thescreen no matter what widget gets that key. To bind an event at the applicationlevel, call the .bind_all() method on any widget (see Universal methods, above).Here’s how you might bind the sc PrintScrn key, whose “key name” is "Print":self.bind_all ( "", self.__printScreen )New Mexico Tech Computer Center <strong>Tkinter</strong> <strong>reference</strong>: Events Page 77

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!