[Tutor] Multiple buttons, One callback

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sat Sep 17 00:27:55 CEST 2005



> I've been able to bind each button to the same callback function (that
> part's trivial) but what hasn't been trival is determining which button
> was clicked and, from this information, gathering the correct datum from
> the list of StringVars which make up the first label text.


Hi David,

It's possible to make dynamic callbacks.  For example:

######
>>> def some_function(x):
...     print "I see", x
...
>>> def make_callback(n):
...     def callback():
...         return some_function(n)
...     return callback
######


make_callback() is a function that returns a "thunk" callback.  That
returned thunk doesn't take an argument, so it's perfectly appropriate as
a button callback.

And yet, that callback can remember what was initially passed into
make_callback() --- it remembers the datum that we used to build the
thunk.  Here, take a look:

######
>>> callbacks = [make_callback(i) for i in range(5)]
>>> callbacks[0]
<function callback at 0x403a610c>
>>> callbacks[0]()
I see 0
>>> callbacks[1]
<function callback at 0x403a6bfc>
>>> callbacks[1]()
I see 1
######

Does this make sense?  Please free to ask questions about this.


Good luck!



More information about the Tutor mailing list