Search code examples
pythontkinteroptgroup

Possible to create a dropdown menu in tkinter/ttk with HTML optgroup-style grouping of options?


I want to create a dropdown menu using tkinter from a dictionary of arrays, where I want the keys to represent higher-level groups for the menu choices, and strings inside the value arrays to represent the actual choices available to the user. In other words, when the dropdown is clicked, the dropdown should resemble one created in HTML using the optgroup tag, where there are both unselectable labels functioning as group titles and selectable labels functioning as the actual choices.

My dictionary looks something like this:

ingredients = {
    "Herbs":
        ["basil",
        "oregano",
        "thyme"],
     "Meats":
        ["chicken",
          "beef",
          "venison",],
     "Spices":
        ["pepper",
          "salt",
          "chilli powder",
          "cumin"]
    }

The user should be able to choose 'basil', 'beef', 'salt' etc. from the dropdown but not 'Herbs', 'Meats', or 'Spices', which should only be present as static titles for the different groups of ingredients. Is this possible using just tkinter/ttk?


Solution

  • May be this would help you atleast

    from tkinter import *
    
    root = Tk()
    root.title("Tk dropdown example")
    
    mainframe = Frame(root)
    
    mainframe.grid()
    
    tkvar = StringVar(root)
    
    ingredients = {
        "Herbs":
            ["basil",
            "oregano",
            "thyme"],
         "Meats":
            ["chicken",
              "beef",
              "venison",],
         "Spices":
            ["pepper",
              "salt",
              "chilli powder",
              "cumin"]
        }
    c=[]
    for k,v in ingredients.items():
        c.append(k)
        c.extend(v)
    ddl = OptionMenu(mainframe, tkvar, *c)
    Label(mainframe, text="Choose a dish").grid(row = 1, column = 1)
    ddl.grid(row = 2, column =1)
    for i in ingredients:
            ddl['menu'].entryconfigure(i, state = "disabled",font=('arial italic',11))
    
    root.mainloop()