Sometimes 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 whose widgets are stored in a
self.cbList, indexed by the
checkbutton number in
Suppose further that you want to write one handler named
<Button-1> events in all ten of these
checkbuttons. The handler can get the actual
Checkbutton widget that triggered it by
referring to the
.widget attribute of the
Event object that gets passed in, but how
does it find out that checkbutton's index in
It would be nice to write our handler with an extra argument for 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 function above because of a mismatch in the number of arguments.
Fortunately, Python's ability to provide default values for function arguments gives us a way out. Have a look at this code:
def __createWidgets(self): … self.cbList =  # Create the checkbutton list for i in range(10): cb = tk.Checkbutton(self, …) self.cbList.append(cb) cb.grid( row=1, column=i) def handler(event, self=self, i=i): return self.__cbHandler(event, i) cb.bind('<Button-1>', handler) … def __cbHandler(self, event, cbNumber): …
|These lines define a new function
This technique can be extended to supply any number of additional arguments to handlers.