[Tutor] Multiple buttons, One callback (fwd)

Kent Johnson kent37 at tds.net
Sat Aug 5 01:00:48 CEST 2006

Michael Lange wrote:
>> ---------- Forwarded message ----------
>> Date: Fri, 4 Aug 2006 09:32:48 -0700 (PDT)
>> From: Michael Cochez <michaelcochez at yahoo.com>
>> To: dyoo at hkn.eecs.berkeley.edu
>> Subject: Multiple buttons, One callback
>> Hi Danny,
>> I've just been reading your reply on this subject at
>> http://mail.python.org/pipermail/tutor/2005-September/041358.html
>> about a year ago.
>> I need something like this but also something more:
>> I'm making an app with an interface that is going to
>> look like in the added image. The "=" buttons are
>> there to copy the contents of the previous lines to
>> the current line.
>> To make the buttons tried a lot of things but the
>> problem is: the number of buttons is always different
>> (one less as the number of day) so it can be none or
>> 20 or something else. So i putted the creation in a
>> for loop.
>> But now the real problem: every button must have its
>> own callback(because the linenumber is different) So
>> my question is: how can I give each button its 'own'
>> callback while only having one (the callbacks are all
>> the same but with another value of linenumber. I added
>> a piece of the code to show what i mean.
> I would use a lambda for this, like:
> def makeidentical(linenumber):
>     print "the linenumber is: %d" % (linenumber)
> for day in datelist:
>     a=datelist.index(day)
>     if a>0:#on every line exept the first
>         identicalbutton=Button(frame2,text="=",command=lambda : makeidentical(a))
You have to bind the current value of a in the lambda, otherwise all the 
callbacks will use the final value of a. One way to do this is with a 
default argument to the lambda:

  identicalbutton=Button(frame2,text="=",command=lambda a=a : makeidentical(a))

Another way is with a separate function such as make_callback in the original post.



More information about the Tutor mailing list