Today's tutorial is going to focus on two commonly used Tkinter widgets -- Checkbutton
and Radiobutton
. Buttons can be seen everywhere in GUI applications. They are useful for allowing users to interact with an application, creating options and choices for a user to select. In a previous tutorial we took a look at using the Tkinter Button widget.
GUI showing Checkbutton and Radiobutton widgets in Tkinter.
Creating Checkbutton
Widgets
Checkbuttons are a very commonly used widget. They are great whenever a user needs to select multiple items in the GUI window, or when you need to control a feature of an application, switching it on and off with the checkbutton. This functionality is useful when you want to enable/disable features such as showing or hiding a toolbar.
Checkbutton
widgets can also be used to call Python methods or custom-made functions using the command
argument. Every checkbutton needs to have a corresponding variable associated with it. Control variables created using the variable classes -- IntVar
, DoubleVar
, BooleanVar
, and StringVar
-- can be used to keep track of changes to Tkinter widgets.
Let's take a look at a small snippet of code that sets up a Checkbutton
.
var = IntVar() # variable class
item1 = Checkbutton(root, text="tuna fish",
variable=var, command=selectItems)
item1.pack(anchor='w')
def selectItems():
print(var.get()) # prints 1 or 0
if var.get(): # If the button is checked,
print(item1['text']) # Print print the cb's text
First, we create the integer variable, var
, which is used to monitor the state of the checkbutton. Next, we create an instance of Checkbutton
. For parameters, we set its root
parent widget, the text
, the variable
associated with the widget, and the function it will call when the user interacts with it. Lastly, we use pack()
to arrange the widget in the window.
In the selectItems()
method, we use get()
to read the variable's current value. If you ever want to specify the value of a variable, then use the set()
method.
Create GUI Applications with Python & Qt6 by Martin Fitzpatrick — (PySide6 Edition) The hands-on guide to making apps with Python — Over 10,000 copies sold!
Creating Radiobutton
Widgets
Whereas the Checkbutton
widget is useful for selecting a number of choices, the Radiobutton
is generally used for picking one choice out of many. Radiobuttons can also be used to call Python functions when clicked on.
In order to achieve exclusivity among the radiobuttons in a group, they should share the same variable. This means that when one radiobutton in a group is selected any other selected widgets will be deselected. You can see this demonstrated in the bit of code below.
Label(root, text="Select your country of birth: ").pack(anchor='w')
var1 = StringVar(root, "USA") # Create a variable for strings, and initialize the variable
Radiobutton(root, text="USA", variable=var1, value="USA", command=printResults).pack(anchor='w')
Radiobutton(root, text="France", variable=var1, value="France", command=printResults).pack(anchor='w')
Radiobutton(root, text="Germany", variable=var1, value="Germany", command=printResults).pack(anchor='w')
Radiobutton(root, text="China", variable=var1, value="China", command=printResults).pack(anchor='w')
def printResults():
print(var1.get())
You can see how the radiobutton widgets look in the following image.
Tkinter Radiobutton example.
The process for creating radiobuttons is similar to checkbuttons. One additional parameter we need to pass is the value
associated with each individual radiobutton. If you have a bunch of radiobutton widgets you need to create, try using a for
loop to instantiate them.
A Simple GUI Example
Now let's take a look at an example that combines the Checkbutton
and Radiobutton
widgets into a very simple food ordering GUI.
We use Object-Oriented Programming (OOP) in the following program. If you are not familiar with OOP, please check out Python documnentation on using classes or other online tutorials to help get you started.
from tkinter import (Tk, ttk, Label, Frame, Button,
Checkbutton, Radiobutton, IntVar, HORIZONTAL)
class SimpleGUI(Tk):
def __init__(self):
super().__init__()
self.initializeUI()
def initializeUI(self):
self.title("Food Order Form")
self.minsize(300, 200) # width, height
self.geometry("400x350+50+50")
self.setupWindow()
def setupWindow(self):
""" Set up the widgets."""
title = Label(self, text="Food Order Form",
font=('Helvetica', 20), bd=10)
title.pack()
line = ttk.Separator(self, orient=HORIZONTAL)
line.pack(fill='x')
order_label = Label(self, text="What would you like to order?", bd=10)
order_label.pack(anchor='w')
foods_list = ["Sandwich", "Salad", "Soup", "Pizza"]
self.foods_dict = {}
# Populate the dictionary with checkbutton widgets
for i, food_item in enumerate(foods_list):
# Set the text for each checkbutton
self.foods_dict[food_item] = Checkbutton(self, text=food_item)
# Create a new instance of IntVar() for each checkbutton
self.foods_dict[food_item].var = IntVar()
# Set the variable parameter of the checkbutton
self.foods_dict[food_item]['variable'] = self.foods_dict[food_item].var
# Arrange the checkbutton in the window
self.foods_dict[food_item].pack(anchor='w')
payment_label = Label(self, text="How do you want to pay?", bd=10)
payment_label.pack(anchor='w')
# Create integer variable
self.var = IntVar()
self.var.set(0) # Use set() initialize the variable
self.payment_methods = ["PayPal", "Credit Card", "Other"]
for i, method in enumerate(self.payment_methods):
self.pymt_method = Radiobutton(self, text=method, variable=self.var, value=i)
self.pymt_method.pack(anchor='w')
# Use ttk to add styling to button
style = ttk.Style()
style.configure('TButton', bg='skyblue', fg='white')
# Create button that will call the method to display text and
# close the program
next_button = ttk.Button(self, text="Next", command=self.printResults)
next_button.pack()
def printResults(self):
"""Print the results of the checkboxes and radio buttons."""
for cb in self.foods_dict.values():
if cb.var.get():
print('Item selected: {}'.format(cb['text']))
index = self.var.get()
print("Payment method: {}".format(self.payment_methods[index]))
self.quit()
if __name__ == "__main__":
app = SimpleGUI()
app.mainloop()
The complete GUI can be seen in the image at the beginning of this tutorial.
Explanation
Start by importing the modules we need from tkinter
. We need to create a class for our window, SimpleGUI
, that inherits from Tk
. Next, initialize the interface's parameters.
In the setupWindow()
method, we set up the Label
, Checkbutton
, and Radiobutton
widgets, and their respective variables. A for
loop is used to create each checkbutton instance. Refer to the code for comments about how to set up the Checkbutton
widgets. The next widgets we need to create are the radiobuttons. By sharing the var
object, we create a mutually exclusive group of radiobuttons. Mutual exclusivity refers to the theory in probability that two or more events cannot occur at the same time.
Finally, when the next_button
is clicked, the printResults()
method is called. This prints the text from selected checkbuttons and radiobutton and closes the program.
Output to the Terminal window.
Summary
In this tutorial we take a brief look at the Checkbutton
and Radiobutton
widgets. These two kinds of widgets are useful for allowing a user to select choices from a group of options. Checkbuttons are typically used when a user needs to be able to select multiple selections. Radiobuttons are best used when a user only needs to select one choice from many.
For more information about Tkinter or the Checkbutton
and Radiobutton
widgets, check out the Python documentation on Tkinter.
Never miss an update
Enjoyed this? Subscribe to get new updates straight in your Inbox.