假设我有一个选项菜单network_select
,其中包含要连接的网络列表。
import Tkinter as tk
choices = ('network one', 'network two', 'network three')
var = tk.StringVar(root)
network_select = tk.OptionMenu(root, var, *choices)
现在,当用户按下刷新按钮时,我想更新用户可以连接到的网络列表。
.config
,因为我查看了network_select.config()
并没有看到一个看起来像我给它的选项。ListVar
这样的东西。我修改了您的脚本以演示如何执行此操作:
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中的选项。
相同,但与tk.Menu
小部件:
# Using lambda keyword and refresh function to create a dynamic menu.
import tkinter as tk
def show(x):
""" Show menu items """
var.set(x)
def refresh(l):
""" Refresh menu contents """
var.set('')
menu.delete(0, 'end')
for i in l:
menu.add_command(label=i, command=lambda x=i: show(x))
root = tk.Tk()
menubar = tk.Menu(root)
root.configure(menu=menubar)
menu = tk.Menu(menubar, tearoff=False)
menubar.add_cascade(label='Choice', menu=menu)
var = tk.StringVar()
l = ['one', 'two', 'three']
refresh(l)
l = ['four', 'five', 'six', 'seven']
tk.Button(root, text='Refresh', command=lambda: refresh(l)).pack()
tk.Label(root, textvariable=var).pack()
root.mainloop()
在使用ttk的情况下,OptionMenu对象上有一个方便的set_menu(default=None, values)
方法。