Changing the selected item of an OptionMenu programmatically

我与影子孤独终老i 提交于 2019-12-25 16:58:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!