I am using Tkinter to build a form with some conditional logic. There are two Option Menus, and the options available in the second depend on the user's selection in the first. For some reason, however, the default option in the first menu disappears once the user selects a different option. For example, if the user selects category B in the reprex below, they can change to C or back to B, but they cannot change back to A.
Can someone help me understand why this is happening?
from tkinter import *
from tkinter import ttk
def update_options(self, *args):
list = dict[first_category.get()]
second_category.set(list[0])
menu = optionmenu_b['menu']
menu.delete(0, 'end')
for item in list:
menu.add_command(label=item, command=lambda selection=item: second_category.set(selection))
window = Tk()
style = ttk.Style(window)
style.theme_use("aqua")
dict = {'A':
['A1', "A2"],
'B':
['B1', 'B2'],
'C':
['C1', 'C2']}
first_category = StringVar()
second_category = StringVar()
optionmenu_a = ttk.OptionMenu(window, first_category, *dict.keys())
optionmenu_b = ttk.OptionMenu(window, second_category, '')
for item in dict['A']:
optionmenu_b['menu'].add_command(label=item, command=lambda selection=item: second_category.set(selection))
first_category.trace('w', update_options)
optionmenu_a.grid(row = 0, column = 1)
optionmenu_b.grid(row = 1, column = 1)
ttk.Label(window, text = "First Label:").grid(row = 0, column = 0)
ttk.Label(window, text = "Second Label:").grid(row = 1, column = 0)
window.title('Options')
window.geometry("500x500 10 10")
window.mainloop()
CodePudding user response:
You didn't set a default option so tkinter takes the first option out of the dictionary which is A, and thinks it is what should be shown when the user didn't choose anything yet. To avoid this, you can set a default option in ttk.OptionMenu like this:
optionmenu = ttk.OptionMenu(root, variable, default_option, *options)
So your OptionMenu would look like this:
optionmenu_a = ttk.OptionMenu(window, first_category, 'A', *dict.keys())
Instead of this:
optionmenu_a = ttk.OptionMenu(window, first_category, *dict.keys())