Event Binding 1

Happily, lambda also gives us a way to parameterize event binding. Instead of:

self.button1.bind("", self.buttonHandler a(event, button name, 1, "Good stuff!"))

(which wouldn't work, because there was no way to include the event argument in the argument list), we can use lambda, this way:

# event binding -- passing the event as an argument self.button1.bind("", lambda event, arg1=button name, arg2=1, arg3="Good stuff!" : self.buttonHandler a(event, arg1, arg2, arg3) )

[Note that "event" here is a variable name -- it is not a Python keyword or anything like that. This example uses the name "event" for the event argument, but some discussions of this technique use the name "e" for the event argument, and we could just as easily have called it "event_arg" if we had wanted to.]

One of the nice features of using lambda is that we can (if we wish), simply not pass the event argument. If we don't pass the event argument, then we can call the self.buttonHandler function directly, instead of indirectly through the self.buttonHandler_a function.

To illustrate this technique, we will code the event binding for button2 differently than we did for buttonl. This is what we do with button2:

# event binding -- without passing the event as an argument self.button2.bind("", lambda event, arg1=button name, arg2=2, arg3="Bad stuff!" : self.buttonHandler(arg1, arg2, arg3) )

0 0

Post a comment

  • Receive news updates via email from this site