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.

def __drawOrangeBlob ( self, event ):"""Draws an orange blob in self.canv where the mouse is."""r = 5 # Blob radiusself.canv.create_oval ( event.x-r, event.y-r,event.x+r, event.y+r, fill="orange" )When this handler is called, the current mouse position is (event:x; event:y). The.create_oval() method draws a circle whose bounding box is square and centered onthat position and has sides of length 2*r.22.7 The extra arguments trickSometimes you would like to pass other arguments to a handler besides the event.Here is an example. Suppose your application has an array of ten checkbuttons whosewidgets are stored in a list self.cbList, indexed by the checkbutton number in therange [0, 9].Suppose further that you want to write one handler named .__cbHandler <strong>for</strong> events in all ten of these checkbuttons. The handler can get the actual Checkbuttonwidget that triggered it by referring to the .widget member of the Event object that getspassed in, but how does it find out that checkbutton’s index in the self.cbList array?It would be nice to write our handler with an extra argument <strong>for</strong> the checkbutton number,something like this:def __cbHandler ( self, event, cbNumber ):But event handlers are passed only one argument, the event. So we can’t use the functionabove because of a mismatch in the number of arguments.Fortunately, <strong>Python</strong>’s ability to provide default values <strong>for</strong> function arguments gives us away out. Have a look at this code:1def __createWidgets ( self ):2: : :3self.cbList = [] # Create the checkbutton list4<strong>for</strong> i in range(10):5cb = Checkbutton ( self, : : : )6self.cbList.append ( cb )7cb.grid( row=1, column=i )8def handler ( event, self=self, i=i ):9return self.__cbHandler ( event, i )10cb.bind ( "", handler )11: : :12def __cbHandler ( self, event, cbNumber ):Lines 8–9 define a new function handler that expects three arguments. The first argumentis the Event object passed to all event handlers, and the second and third arguments willbe set to their default values—the extra arguments we need to pass it.This technique can be extended to supply any number of additional arguments to handlers.New Mexico Tech Computer Center <strong>Tkinter</strong> <strong>reference</strong>: Events Page 83

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

Saved successfully!

Ooh no, something went wrong!