问题
I have defined a simple OptionMenu
like
import Tkinter as tk
optionList = ('a', 'b', 'c')
v = tk.StringVar()
v.set(optionList[0])
om = tk.OptionMenu(self, v, *optionList)
This list will appear with a
as default which is fine. But there are also command buttons defined which eventually need to alter this to show another of the available options (say b
). How can this be achieved?
回答1:
You already found a way to set a default value and change it. You have the v
variable associated to that OptionMenu
widget. If at any time you change the value of that variable again, it will update your widget:
import tkinter as tk
root = tk.Tk()
optionList = ('a', 'b', 'c')
v = tk.StringVar()
v.set(optionList[0]) # Here is the initially selected value
om = tk.OptionMenu(root, v, *optionList)
om.pack()
v.set(optionList[2]) # This one will be the final selected value
root.mainloop()
来源:https://stackoverflow.com/questions/44138026/changing-the-selected-item-of-an-optionmenu-programmatically