Search code examples
pythontkintermenuradio-button

How to use add_radiobutton() to cascade in Menu() from Tkinter to set a default checkmark next to one of the values?


When program starts with the default size, for example 10x10, in the size submenu the checkmark should already be in front of the 10x10 line. Need to initially specify one of the options, and then to be able to choose any option.

from tkinter import Tk, Menu

root = Tk()
menubar = Menu(root)
size = Menu(menubar, tearoff=0)
size.add_radiobutton(label='5x5')
size.add_radiobutton(label='10x10')  # <- Checkmark must be here when program starts.
                                     # When choosing another option, it must be unmarked,
                                     # like in this example
size.add_radiobutton(label='15x15')
menubar.add_cascade(label='Size', menu=size)
root.config(menu=menubar)
root.mainloop()

Solution

  • The radiobuttons need a Tk variable to group the buttons. The code below uses an IntVar. The result is reported in a Label.

    import tkinter as tk
    
    root = tk.Tk()
    root.geometry( '100x100')
    radio_var = tk.IntVar( value = 10 )  # Option 10 is the default.
    
    menubar = tk.Menu(root)
    size = tk.Menu(menubar, tearoff=0)
    size.add_radiobutton(label='5x5', variable = radio_var, value = 5 )
    size.add_radiobutton(label='10x10', variable = radio_var, value = 10 )
    size.add_radiobutton(label='15x15', variable = radio_var, value = 15 )
    menubar.add_cascade(label='Size', menu=size)
    root.config(menu=menubar)
     
    lab = tk.Label( root, textvariable = radio_var )
    lab.grid()
    
    root.mainloop()