I have a program which dynamically generates a GUI. I don't know how many buttons I will have, if any at all.
The specific problem is something like this:
for varname in self.filetextboxes:
if self.varDict[varname]=='':
self.varDict[varname] = (StringVar(),)
self.varDict[varname][0].set('')
fileButton = Button(self, text=" ", command = lambda:self.varDict[varname][0].set(tkFileDialog.askopenfilename()), image=self.filephoto)
ftb = Entry(self, textvariable = self.varDict[varname][0],width=40,background='white')
I have a for loop which creates the textboxes and the buttons.
The StringVar() is stored in a dictionary with key varname
.
because I can't pass arguments in the callback function of the button, I instead define a lambda in each button. This sets the StringVar() associated with the textbox created in this loop to the output of a filedialog box.
The problem is, the varname passed to the lambda isn't passing the value, but the name of the variable only. So while the textboxes are associated with the variable they were created with in the for loop, lambdas in the buttons uses the current value of varname at all times.
In other words, each textbox links to only one variable, but all the buttons only set the text of the final textbox created, i.e. the textbox with the final value of varname.
Is there another way to approach this? Can I make the lambda somehow only use the value of varname as it is defined, and not use future values of varname?