I want to make 5 buttons in a loop, and for each buttons bind a commend to print the index. In the following solution it always prints the same index.
My code like this:
for i in range(5):
make_button = Tkinter.Button(frame, text ="make!",
command= lambda: makeId(i))
def makeId(i):
print(i)
It always prints 5. How can I fix this?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Resolution of variables in lambdas is done when lambda is executed. At this time, for all buttons i=5. To rectify this issue do as follows:
make_button = Tkinter.Button(frame, text ="make!",
command= lambda i=i: makeId(i))
This creates i as a local variable in a lambda. This local variable will hold correct value of i from the loop. the local variable can have any name, not necessarily i, e.g. command= lambda a=i: makeId(a)).
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0