Tkinter Checkbutton – Get selected values

Tkinter – Get text values of selected Checkbuttons

To get the text values of all the selected Checkbutton widgets in Tkinter, get the variables associated with the Checkbuttons and find those that are selected.

For example, consider that we created Checkbutton widgets using a dictionary, like the one shown in the following.

options = {
    "Option 1": tk.IntVar(),
    "Option 2": tk.IntVar(),
    "Option 3": tk.IntVar()
}

Now, in the callback function of an event in which you would like to get the selected values, use a For loop statement as shown in the following.

selected_options = []
for option, var in options.items():
    if var.get() == 1:
        selected_options.append(option)

In the For loop statement, we iterate over the variables of the Checkbutton widgets, and collect the values of the selected Checkbuttons in a list selected_options.

In this tutorial, you shall learn how to get the text values of selected Checkbuttons in Tkinter, with examples.

Example

In this example, we shall create three Checkbuttons using a dictionary, and a button Show Selected. When user clicks on the Show Selected button, we print the text values of the selected Checkbuttons.

Python Program

import tkinter as tk

def show_selected():
    selected_options = []
    for text, var in options.items():
        if var.get() == 1:
            selected_options.append(text)
    print("Selected options:", selected_options)

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

# Text and Variable for Checkbuttons
options = {
    "Option 1": tk.IntVar(),
    "Option 2": tk.IntVar(),
    "Option 3": tk.IntVar()
}

# Create Checkbuttons in a loop
for option, var in options.items():
    check_button = tk.Checkbutton(root, text=option, variable=var)
    check_button.pack(anchor=tk.W)

button = tk.Button(root, text="Show Selected", command=show_selected)
button.pack()

# Start the Tkinter event loop
window.mainloop()
Copy

Output in MacOS

Tkinter Checkbutton - Get selected values - Example
Three Checkbutton widgets

User selects Option 2.

User selects a Checkbutton
User selects “Option 2”

The callback function show_selected executes, and prints the list of selected options.

Terminal Output when user selects Checkbutton "Option 2", and clicks on "Show Selected" button
Terminal Output

User selects another option, Option 3.

User selects another Checkbutton
User selects “Option 3” also

The callback function show_selected executes, and prints the list of selected options.

Terminal Output when user selects Checkbutton "Option 3" also, and clicks on "Show Selected" button
Terminal Output

Summary

In this Python Tkinter tutorial, we have seen how to get the text values of selected Checkbutton widgets in Tkinter, with examples.

Code copied to clipboard successfully 👍