Reputation: 376
So, basically i have this code:
class Top(Frame):
def __init__(self,master):
Frame.__init__(self,master)
self.num = 10
self.items = range(6)
self.pack()
self.widgets()
def widgets(self):
menu = Toplevel()
frame = Frame(menu,padx=5,pady=5)
variables = []
menus = []
callbacks = []
def assign():
pass
for i in range(self.num):
Label(frame,text=str(i)).grid(sticky='W',row = i,column=0)
variables.append(StringVar(""))
menus.append(OptionMenu(frame,variables[i],""))
callbacks.append(assign)
menus[i].configure(width=10)
menus[i].grid(sticky='W',row = i,column=1)
for item in self.items:
menus[i]["menu"].add_command(label=str(item),command=callbacks[i])
variables[i].set(str(i*i))
frame.grid()
menu.grid()
root = Tk()
top = Top(root)
top.mainloop()
Now, when I click on one of the entries, it does not change to this specific entry. What am I overlooking? It is structured like that because the number of the entries and the corresponding items in the OptionMenus AND the callbacks are dynamically changing with each call. Also, if the entry actually changes, what is the best way to get the current entry?
Regards,Kai
Upvotes: 0
Views: 900
Reputation: 385890
You aren't using OptionMenu
correctly. You are removing all of its built-in behavior. The proper way to create an OptionMenu
is to give it all of the items at the time you create the widget. Internally, the OptionMenu
will use the command
attribute of each menu item to manage the value. By creating your own menu items with their own commands, you are preventing the widget from working properly.
There's nothing wrong with creating your own menubutton with a menu (which is all that the OptionMenu is...), but if you do so then you'll have to take care of the detail of making sure the menubutton label matches the value. If you want the automatic behavior, you need to use the OptionMenu
as it was intended to be used.
A decent tutorial can be found here: http://effbot.org/tkinterbook/optionmenu.htm
Upvotes: 1