Issue
I want to create a menu in tkinter that lists names from a csv file. I am using a lambda function, but I cannot figure out how to make the buttons do different things. They all do the same thing as the last one since it was the last one created. Here is some code to demonstrate:
from tkinter import *
def printindex(x):
print(x)
root = Tk()
menu = Menu(root)
file = Menu(menu)
for i in range(10):
file.add_command(label=str(i), command=lambda: printindex(i))
menu.add_cascade(label="File", menu=file)
root.config(menu=menu)
root.mainloop()
When I run this, all of the options in the menu print 9.
I want all the items in the menu to point to the same function but pass in their respective values. How would I do this?
Solution
The values of variables used in closures are looked up when the function is called, and in your case the value of i
is 9. You can modify your lambda function to force a closure:
command=lambda i=i: printindex(i)
Answered By - Henry Yik Answer Checked By - Senaida (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.