Changing the options of a OptionMenu when clicking a Button
35,092
Solution 1
In case of using ttk, there is a convenient set_menu(default=None, values)
method on the OptionMenu object.
Solution 2
The same, but with tk.Menu
widget:
# 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()
Author by
charmoniumQ
Updated on January 26, 2021Comments
-
charmoniumQ over 3 years
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.
- 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 don't I can use