Reputation: 11
I'm very confused about this widget, can someone fix it ?
from Tkinter import *
master = Tk()
mytext = StringVar()
mytext.set("DEFAULT")
def test_function(evt):
mb.menu.delete(0, END)
for i in range(20):
mb.menu.add("command", label='%s'%i, command= lambda : mytext.set("%s"%i))
mb= Menubutton (master, text="Test", relief=RAISED )
mb.menu = Menu ( mb, tearoff = 0 )
mb["menu"] = mb.menu
mb.bind('<Button-1>', test_function)
mb.grid(row = 0, column=1)
Label(master, textvariable=mytext).grid(row = 0, column=0)
master.mainloop()
mytext
always show the end of the list when selected the button how to solve it?
Upvotes: 0
Views: 157
Reputation: 76194
mb.menu.add("command", label='%s'%i, command= lambda : mytext.set("%s"%i))
The i
in the command
lambda here binds to the last value that i
had, rather than the value it had when you called add
.
You can trick it into binding early by making it a default argument:
mb.menu.add("command", label='%s'%i, command= lambda i=i: mytext.set("%s"%i))
Upvotes: 1