Search code examples
pythontkinterdrop-down-menu

How to create an option menu in Tkinter?


How can I make an option field in Tkinter?

For example, in HTML it is this:

<select>
  <option value="Option1">Option1</option>
  <option value="Option2">Option2</option>
  <option value="Option3">Option3</option>
  <option value="Option4">Option4</option>
</select>

Solution

  • Method 1: OptionMenu

    The first method is to use OptionMenu from tkinter. You will have to create a list containing all your desired options. Then you need to have a variable that holds the information regarding which button is currently selected.

    Useful resource: How can I create a dropdown menu from a List in Tkinter?

    Sample code:

    from tkinter import *
    
    root = Tk()
    root.geometry("300x300")
    
    OPTIONS = [
    "Option 1",
    "Option 2",
    "Option 3"
    ] #etc
    
    variable = StringVar()
    variable.set(OPTIONS[0]) # default value
    
    w = OptionMenu(root, variable, *OPTIONS)
    w.pack()
    
    root.mainloop()
    

    Output:

    enter image description here

    Method 2: Radiobutton

    You can use Radiobutton in tkinter to have options.

    The arguments that you need to pass in are the window which is root, the text to be displayed in the option button, a shared variable which holds the information regarding which button is currently selected, and unique value to distinguish this radio button.

    Note: each radio button should have a different unique value otherwise more than one radio button will get selected.

    Parameters to be passed in:

    button = Radiobutton(root, text="Name on Button", variable = “shared variable”, value = “values of each button”)
    

    Useful resources regarding Radiobutton -

    1. Radio button values in Python Tkinter
    2. https://www.geeksforgeeks.org/radiobutton-in-tkinter-python/#:~:text=The%20Radiobutton%20is%20a%20standard,calls%20that%20function%20or%20method.

    Sample code:

    from tkinter import *
    import tkinter as tk
    
    root = Tk()
    root.geometry("300x300")
    
    payment_method_label=Label(root, text="Select Payment Method:")
    
    payment_method = StringVar()
    payment_method.set("card")
    
    cards = Radiobutton(root, text="Debit/Credit Card", variable=payment_method, value="card").pack(anchor=tk.W)
    wallet = Radiobutton(root, text="Payment Wallet", variable=payment_method, value="wallet").pack(anchor=tk.W)
    netbanking = Radiobutton(root, text="Net Banking", variable=payment_method, value="net banking").pack(anchor=tk.W)
    
    root.mainloop()
    

    Output:

    enter image description here