Tkinter Radiobutton – Set Default Option

Tkinter Radiobutton – Set Default Option

When we create a group of Radiobutton widgets, we set a specific variable to all the radio buttons in the group. Using this variable, we can set a default value for the selection, or in other terms, already select an option in the Radiobutton group.

Tkinter Radiobutton - Set Default Option
Tkinter Radiobutton group – Option 1 is the default selection

To set a default selection for a group of Radiobutton widgets in Tkinter, set the StringVar associated with the Radiobutton widgets with the required default value, as shown below.

radio_var = tk.StringVar(value="Option 1")

In the above code, we created a StringVar with a default value of Option 1. When the Radiobutton widgets associated with this variable are displayed in the GUI, the Radiobutton with the specified value is already selected by default.

In this tutorial, you will learn how to set a default selection for Radiobutton widgets group in Tkinter, with an example program.

Example

In this example, we shall create a group of three Radiobutton widgets with values: Option 1, Option 2, and Option 3. The variable associated with these radio buttons is initialized with the value Option 1. Therefore, the radio button with the value Option 1 is selected by default.

Program

import tkinter as tk

# Create the main window
window = tk.Tk()
window.geometry("300x200")
window.title("PythonExamples.org")

# Create a variable to hold the selected option
radio_var = tk.StringVar(value="Option 1")

# Create Radiobuttons
radio_button1 = tk.Radiobutton(window, text="Option 1", variable=radio_var, value="Option 1")
radio_button2 = tk.Radiobutton(window, text="Option 2", variable=radio_var, value="Option 2")
radio_button3 = tk.Radiobutton(window, text="Option 3", variable=radio_var, value="Option 3")

# Pack the Radiobuttons
radio_button1.pack()
radio_button2.pack()
radio_button3.pack()

# Start the Tkinter event loop
window.mainloop()

Output in Windows

Output on MacOS

Tkinter Radiobutton - Set Default Option
Tkinter Radiobutton group – Option 1 is the default selection

Summary

In this Python Tkinter tutorial, we have seen how to set a default value for Radiobutton group, with examples.

Related Tutorials

Code copied to clipboard successfully 👍