I have a project with a problem that I recreated in this small code
from tkinter import *
top = Tk()
mb= Menubutton ( top, text="condiments", relief=RAISED )
mb.grid()
mb.menu = Menu ( mb, tearoff = 0 )
mb["menu"] = mb.menu
for dressing in ['ketchup','mayo']:
mb.menu.add_command( label=dressing , command=lambda:print(dressing))
mb.pack()
top.mainloop()
so in this example, no matter what I choose in the menu - it prints "mayo" because the last dressing in the loop is mayo and the loop created the menu.
Does anyone have an idea how to fix this issue?
Try this
Adding
d=dressingstores the current value ofdressingin a variabledwhich is sent to theprintstatement.That's the precise reason, when the
lambdafunction was executed later, it took the last assigned value ofdressingwhich in your case happens to bemayoand not the value that it had at the time of assignment.