Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python tkinter change OptionMenu during runtime

My second dropdown list is dependent on my first dropdown list. I can make it work by creating a second OptionMenu that overwrites the first OptionMenu. The following code works.

However, I’m looking for way that will use the same OptionMenu, but will substitute in a new list for the second_choice_proxylist in the second_list.

from tkinter import *
from tkinter import ttk

root = Tk()
root.geometry('400x275')

def option_selected(event):
        if event == option_list[0]:
            option_list2 = first_sublist
        if event == option_list[1]:
            option_list2 = second_sublist
        
        second_list = ttk.OptionMenu(root, second_choice, 'foo or bar', *option_list2)
        second_list.grid(column=2, row=2, sticky=(W, E))

choice_var = StringVar(root)
choice_var.set("Option 1") 
option_list = ["Option 1", "Option 2"]
first_sublist = ['foo1', 'foo2']
second_sublist = ['bar1', 'bar2']

first_list = ttk.OptionMenu(root, choice_var, 'Make a Choice', *option_list, command=option_selected)
first_list.grid(column=2, row=1)
second_choice = StringVar()
second_choice_proxylist = ['Make First Selection First']
second_list = ttk.OptionMenu(root, second_choice, 'Make a Choice', *second_choice_proxylist)
second_list.grid(column=2, row=2)

first_label = ttk.Label(root, text = 'Choose Here First')
first_label.grid(column=1, row=1)
second_label = ttk.Label(root, text = 'Choose Here Second')
second_label.grid(column=1, row=2)

root.mainloop()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use .set_menu() to update the option values of second_list:

def option_selected(event):
    if event == option_list[0]:
        option_list2 = first_sublist
    elif event == option_list[1]:
        option_list2 = second_sublist

    second_list.set_menu('foo or bar', *option_list2)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading