0

so my problem is in this bit of program where I want to create "x" buttons (x is the length of a list), and each button has the name of the element in the list and calls the function "ChoicePage" with the name of the element as argument

example: If I have a list like this [house, hospital, shop], the program creates 3 buttons: house, hospital and shop and they call ChoicePage(a) with a = "house", "hospital" or "shop"

 for i in range(len(L)):

        a = L[i]

        Button(fen1, text=a, relief=RAISED, command = lambda:(ChoicePage(a))).pack()

    fen1.mainloop()

the problem here is that it always calls ChoicePage with the last element of the list (in the previous example it would be "shop")

How can I fix this ?

Bastien
  • 11
  • 1

2 Answers2

1

When you create lambdas in loop they end up bound to same variable (which has value of last loop iteration). You can use partial to bind value to function or some other method of storig value inside function.

from functools import partial
for i in range(len(L)):
        a = L[i]
        Button(fen1, text=a, relief=RAISED, command = partial(ChoicePage, a)).pack()
fen1.mainloop()
mugiseyebrows
  • 4,138
  • 1
  • 14
  • 15
1

What you should do is call lambda like that:

command=lambda m=a: ChoicePage(var=m) 

where var should be the parameter of your ChoicePage function

This way the variable will be stored corresponding to the right button

Thalis
  • 188
  • 2
  • 12