How to Create Radio Buttons in Python with Tkinter?

In this tutorial, I will explain how to create radio buttons in Python with Tkinter. Radio buttons allow users to select a single option from a group of mutually exclusive choices. They are commonly used in user interfaces to present related options. I’ll present a practical example of implementing radio buttons in a Tkinter application along with some best practices.

Radio Buttons in Python Tkinter

Radio buttons are graphical user interface elements that let users pick one option from a collection of choices. They are called “radio buttons” because they behave similarly to the push buttons on old car radios – pressing one button deselects the previously selected button in the group.

In Python’s Tkinter library, radio buttons are represented by the Radiobutton widget. To create a set of radio buttons, you need to:

  1. Create a shared variable to hold the selected value
  2. Define each radio button, specifying the shared variable and value
  3. Layout the radio buttons in your application’s window

Let’s get into a concrete example to see how this works in practice.

Read How to use Tkinter Filedialog in Python

Create Radio Buttons in Python with Tkinter

Imagine you’re building a Tkinter application to help users select their favorite US city from a list. Radio buttons are a natural fit for this UI, as the user should only be able to pick a single city. Here’s how you could implement this:

import tkinter as tk

root = tk.Tk()
root.title("Select Your Favorite City")

# Create shared StringVar to hold selected value
selected_city = tk.StringVar()

# Define a list of city options 
cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]

# Create radio buttons for each city
for city in cities:
    tk.Radiobutton(root, text=city, variable=selected_city, value=city).pack()

# Add a button to submit selection and print value
def print_selection():
    print(f"You selected: {selected_city.get()}")

submit = tk.Button(root, text="Submit", command=print_selection)
submit.pack()

root.mainloop()

I have executed the above example code and added the screenshot below.

Radio Buttons in Python with Tkinter

Let’s break this down:

  • First, we create a Tk root window and give it a title.
  • We then create a StringVar named selected_city to store the value of the selected radio button.
  • We define a list cities containing the names of some major US cities.
  • We loop through cities and for each one, create a Radiobutton widget. We specify the root window as the first argument, the city name as the text label, selected_city as the variable to be set, and the city name as the value for that variable when selected. We immediately .pack() each radio button to add it to the window.
  • We define a print_selection() function that retrieves the selected value from selected_city using .get() and prints it.
  • We create a “Submit” button that calls print_selection when clicked.
  • Finally, we start the main event loop root.mainloop() to display the window.

When you run this code, you’ll see a window with the city names as radio buttons, and a submit button. Clicking a radio button selects it and deselects any previously selected button. Clicking “Submit” prints the name of the selected city.

Python Tkinter provodes various ways to organize the radio buttons in desired way, Let see some organising methods.

Check out Expense Tracking Application Using Python Tkinter

1. Organize Radio Buttons with Frames

In the previous example, we .pack()ed the radio buttons directly into the root window. For more complex layouts, it’s often helpful to group related widgets into frames. Let’s modify our example to use a LabelFrame to contain our radio buttons:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()  
root.title("Select Your Favorite City")

selected_city = tk.StringVar()

cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]

# Create a LabelFrame for radio buttons
radio_frame = ttk.LabelFrame(root, text="Cities")
radio_frame.pack()

# Create radio buttons inside the LabelFrame
for city in cities:
    ttk.Radiobutton(radio_frame, text=city, variable=selected_city, 
                    value=city).pack()

def print_selection():
    print(f"You selected: {selected_city.get()}")

submit = ttk.Button(root, text="Submit", command=print_selection)
submit.pack()

root.mainloop()

I have executed the above example code and added the screenshot below.

Create Radio Buttons in Python with Tkinter

Here’s what changed:

  • We imported the ttk module to access its themed widgets, like LabelFrame and the styled Radiobutton and Button.
  • We created a LabelFrame named radio_frame, specifying the root window as its parent and “Cities” as its text label. We .pack() it to add it to the root window.
  • In the for loop, we now create each Radiobutton inside radio_frame instead of the root window.

The radio buttons are now neatly contained within a labeled frame, which can help clarify their purpose to the user.

Read Python Tkinter Separator + Examples

2. Set a Default Value in Radio Buttons

Sometimes you may want one of the radio buttons to be selected by default when the application starts. To do this, simply set the shared StringVar to the value of the desired default option:

selected_city.set("Chicago")  # Sets Chicago as default

I have executed the above example code and added the screenshot below.

How to Create Radio Buttons in Python with Tkinter

Now when the window first appears, “Chicago” will already be selected.

Check out How to Generate Payslip using Python Tkinter + Video Tutorial

3. Get the Selected Value in Radio Buttons

In the examples above, we retrieved the selected radio button value in a function called a button press. But you can access the shared variable’s value anytime by calling .get() on it. For instance, you could print the selected value whenever it changes by tracing the variable:

def print_change(*args):
    print(f"Current selection: {selected_city.get()}")

selected_city.trace("w", print_change)
Create Radio Buttons in Python with Tkinter get value

Here, we define a print_change function that prints the current value of selected_city. We then use .trace() to call this function whenever selected_city is written to (the "w" mode). Now, as the user clicks different radio buttons, their selection will be printed immediately.

Read How to convert Python file to exe using Pyinstaller

4. Radio Button command in Python Tkinter

By dynamically generating radio buttons from a list of city names, we achieve a scalable and maintainable design. The application also provides instant feedback when a selection is made, making it interactive and engaging.

from tkinter import *
from tkinter import ttk

# Function to display a message when a city is selected
def sayHello():
    selected_city = cities[var.get()]
    label.config(text=f"Hello from {selected_city}!")

# Create the main window
ws = Tk()
ws.title("USA Cities Guide")
ws.geometry('350x250')

# List of cities
cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]

# Variable to store the selected radio button's value
var = IntVar()
var.set(0)  # Default selection

# Create a LabelFrame for radio buttons
radio_frame = ttk.LabelFrame(ws, text="Cities")
radio_frame.pack(padx=10, pady=10, fill="both", expand="yes")

# Add radio buttons dynamically from the cities list
for index, city in enumerate(cities):
    Radiobutton(radio_frame, text=city, variable=var, value=index, command=sayHello).pack(anchor="w")

# Label to display the message
label = Label(ws, text="Please select a city.")
label.pack(pady=10)

# Run the main event loop
ws.mainloop()
Create Radio Buttons in Python with Tkinter command

This example showcases a clean and modular way to create a Tkinter GUI for selecting a city using dynamically generated radio buttons.

Check out Create Word Document in Python Tkinter

5. Radio Button grid in Python Tkinter

Grid is a positioning manager tool. It positions the widget in a row and column format. the position starts from the top-left corner. the position starts from the top-left corner. that means, row=0 and column=0.

from tkinter import *

ws = Tk()
ws.title('USA Cities Guide')
ws.geometry('200x200')

var = IntVar()
frame = LabelFrame(ws, text='Choose wisely')
frame.pack(pady=10)

Radiobutton(frame, text='Los Angeles', variable=var, value=1).grid(row=0, column=1)
Radiobutton(frame, text="New York", variable=var, value=2).grid(row=0, column=2)
Radiobutton(frame, text="Houston", variable=var, value=3).grid(row=1, columnspan=3)

ws.mainloop()
Create Radio Buttons in Python with Tkinter grid

In this output, we can see that radio buttons are positioned using grid.

Read Python Tkinter Filter Function()

6. Radio Button horizontal in Python Tkinter

Python Radio buttons can be aligned in horizontal or vertical form. In this section, we will learn how to set the radio button in a horizontal form with the help of grid().

from tkinter import *

ws = Tk()
ws.title("USA Cities Guide")
ws.geometry('200x200')

var = IntVar()

cold_bev = Radiobutton(ws, text="Los Angeles", variable=var, value=1).grid(row=0, column=1)
hot_bev = Radiobutton(ws, text="New York", variable=var, value=2).grid(row=0, column=2)

ws.mainloop()

In this output, radio buttons are aligned horizontally. We have used a grid to do so. Here row = 0 and column = 1 for Los Angeles’ and column = 2 for ‘New York’.

Check out Python Tkinter add function with examples

7. Radio Button group in Python Tkinter

Creating a cluster of radio buttons is called a group. The Radiobutton of the same group has the same variable name. In a form, there are multiple radio buttons but they all may not save the same purpose so to categorize them they are grouped like gender will have male and female, stream will have California, Texas, Florida, New York, etc.

from tkinter import *

# Create the main window
ws = Tk()
ws.title("USA Guide")
ws.geometry('300x200')

# Create LabelFrames for Gender and States
frame1 = LabelFrame(ws, text='Gender')
frame1.grid(row=1, column=1, padx=10)

frame2 = LabelFrame(ws, text='State')
frame2.grid(row=1, column=2, padx=10)

# Variables to hold the selected values
group_1 = IntVar()
group_2 = IntVar()

# Gender options
genders = ['Female', 'Male']
for index, gender in enumerate(genders, start=1):
    Radiobutton(frame1, text=gender, variable=group_1, value=index).pack(anchor="w")

# State options
states = ['California', 'Texas', 'Florida', 'New York']
for index, state in enumerate(states, start=1):
    Radiobutton(frame2, text=state, variable=group_2, value=index).pack(anchor="w")

# Run the main event loop
ws.mainloop()

In this output, 2 groups are created for the radio button. Radio buttons inside the ‘Gender‘ won’t affect radio buttons in ‘states‘. Each group is independent.

Read Python Tkinter panel

Best Practices

When working with radio buttons in Tkinter, keep these tips in mind:

  • Use meaningful, concise labels for your radio buttons to convey the options to the user.
  • If you have many radio buttons, consider breaking them up into logical groups using frames.
  • Set a default value if one of the options is the most common or recommended choice.
  • Retrieve the value of the shared variable whenever you need to know the current selection (e.g. when the user clicks a “Submit” or “Next” button).
  • Use .trace() if you need to perform an action immediately whenever the selected option changes.

Check out Python Tkinter after method

Conclusion

In this tutorial, we explored how to create radio buttons in Python with Tkinter. I discussed a simple way to create a radio button later we discussed how to organize radio buttons, how to set a default value, get a selected value, radio button command, radio button grid, radio button horizontal, and radio button group along with important best practices.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.