Search code examples
pythonuser-interfacetkinteroptionmenu

How to clear the value selected in option menu widget of tkinter?


I wanted to add a button to my application to clear all the inputs, so Entry widgets could easily be cleared by delete method and radio buttons can be deselected, but how to deselect an option menu option?


Solution

  • OptionMenu widgets have an associated variable. You can set the variable to anything you want.

    Here's an example with both a tkinter OptionMenu and a ttk OptionMenu:

    import tkinter as tk
    from tkinter import ttk
    
    root = tk.Tk()
    root.geometry("200x200")
    def do_reset():
        om_var.set(om_default)
    
    om_default = "<choose wisely>"
    om_var = tk.StringVar(value=om_default)
    om = tk.OptionMenu(root, om_var, om_default, "one", "two", "three", "four")
    ttk_om = ttk.OptionMenu(root, om_var, om_default, om_default, "one", "two", "three", "four")
    reset = tk.Button(root, text="Reset", command=do_reset)
    
    reset.pack()
    om.pack(fill="x", padx=20, pady=10)
    ttk_om.pack(fill="x", padx=20, pady=10)
    
    root.mainloop()