[Tkinter-discuss] How to set a constant in lambda

david.giesen at kodak.com david.giesen at kodak.com
Thu Jan 29 17:15:58 CET 2009

With lambda, you need to set the value of the variable at the time the 
lambda is created, or else the variable is grabbed from the environment at 
the time the lambda runs.  You can do this by using the variable as a 
default argument.  In your case, change:



XT.append(Button(T,text="Viola:New Tab",command=lambda 

ought to do it.


David J. Giesen | Research Scientist | FPEG US Display OLED Materials R+D 
Eastman Kodak Company | 2/83/KRL MC02216 | Rochester, NY 14650 | 
david.giesen at kodak.com | 1-585-588-0480 Office | 

> From: vtcodger <donaldkenney at gmail.com>
> I came across a problem that probably has a simple, clever, answer -- 
but it
> is eluding me.  I was trying to create a set of tab buttons on a Tkinter
> page using Buttons.  These are created dynamically when the user loads a
> file.  I don't know in advance how many files will get opened, so I want 
> have a variable number of tabs.
> So we have a Frame T; and an array of tabs XT[]; and a function
> switch_tabs(n) that will handle the details of switching the data base,
> titles, etc.  I compute the tab number:
> Whoopsie = len(XT)
> And I create a new Button:
> XT.append(Button(T,text="Viola:New Tab",command=lambda:
> switch_tabs(whoopsie))
> It all works fine except for this one minor detail.  Whoopsie can't be a
> constant because I don't know in advance what constant to use.  And if
> whoopsie is a variable, it apparently is evaluated at execution time, 
> will have the then current value of whoopsie, not the value I wanted to 
> at creation time.  I tried everything I could think of including
> copy.copy(whoopsie) to get a constant set so that switch_tabs could know
> which tab to switch to.
> Couldn't do it.  I was starting to look at tracing back through stack 
> when it came to me that RadioButtons unlike generic Buttons have a
> variable-value attribute pair that behaves as I desire.  So this
> manifestation of the problem is worked around.  But I expect that I'll 
> this problem again in some other guise.
> Am I missing something?  Probably something simple?  What?
> -- 

More information about the Tkinter-discuss mailing list