本文介绍了单击按钮时更改 OptionMenu 的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个选项菜单 network_select
,其中包含要连接的网络列表.
Say I have an option menu network_select
that has a list of networks to connect to.
import Tkinter as tk
choices = ('network one', 'network two', 'network three')
var = tk.StringVar(root)
network_select = tk.OptionMenu(root, var, *choices)
现在,当用户按下刷新按钮时,我想更新用户可以连接到的网络列表.
Now, when the user presses the refresh button, I want to update the list of networks that the user can connect to.
- 我不能使用
.config
,因为我查看了network_select.config()
并没有看到一个看起来像我给它的选择的条目. - 我不认为这是可以使用 tk 变量来改变的东西,因为没有
ListVar
这样的东西.
- I don't I can use
.config
because I looked throughnetwork_select.config()
and didn't see an entry that looked like the choices I gave it. - I don't think this is something one can change using a tk variable, because there is no such thing as a
ListVar
.
推荐答案
我修改了您的脚本以演示如何执行此操作:
I modified your script to demonstrate how to do this:
import Tkinter as tk
root = tk.Tk()
choices = ('network one', 'network two', 'network three')
var = tk.StringVar(root)
def refresh():
# Reset var and delete all old options
var.set('')
network_select['menu'].delete(0, 'end')
# Insert list of new options (tk._setit hooks them up to var)
new_choices = ('one', 'two', 'three')
for choice in new_choices:
network_select['menu'].add_command(label=choice, command=tk._setit(var, choice))
network_select = tk.OptionMenu(root, var, *choices)
network_select.grid()
# I made this quick refresh button to demonstrate
tk.Button(root, text='Refresh', command=refresh).grid()
root.mainloop()
点击刷新"按钮后,network_select 中的选项将被清除,而 new_choices 中的选项将被插入.
As soon as you click the "Refresh" button, the options in network_select are cleared and the ones in new_choices are inserted.
这篇关于单击按钮时更改 OptionMenu 的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!