Search code examples
pythontkinteroptionmenu

is it possible to have an optionmenu inside another optionmenu in tkinter python


I want some items from an optionmenu have further options to choose. I know about menu and menubutton widgets, but these dont help me. I have to use optionmenu


Solution

  • An optionmenu is literally just a menubutton and a menu, with a little bit of syntactic sugar.

    Here's a simple example showing how you can have submenus on something that looks just like an optionmenu:

    import tkinter as tk
    
    root = tk.Tk()
    var = tk.StringVar(value="one")
    menubutton = tk.Menubutton(root, textvariable=var, indicatoron=True,
                               borderwidth=1, relief="raised", width=20)
    main_menu = tk.Menu(menubutton, tearoff=False)
    menubutton.configure(menu=main_menu)
    
    for item in (("Numbers", "one", "two", "three"),
                 ("Colors", "red", "green", "blue")
    ):
        menu = tk.Menu(main_menu, tearoff=False)
        main_menu.add_cascade(label=item[0], menu=menu)
        for value in item[1:]:
            menu.add_radiobutton(value=value, label=value, variable=var)
    
    menubutton.pack(side="top", padx=20, pady=20)
    
    root.mainloop()
    

    If you want the user to be able to pick a different value from each sub-menu, you can just create a new StringVar for each menu. However, you'll have to write some code to update the label of the button yourself.