How to Create Checkboxes in Python Tkinter?

In this tutorial, I will explain how to create checkboxes in Python Tkinter. Checkboxes allow users to make on/off selections, which is useful for gathering input on multiple options. I’ll walk through how to create and customize checkboxes with Tkinter, handle events, and share examples from my own experience building Tkinter apps.

Create a Checkbox in Python Tkinter

To create a checkbox in a Tkinter application, you first need to import the Tkinter module and create an instance of the Checkbutton class. Here’s a simple example that displays a single checkbox:

import tkinter as tk

window = tk.Tk()
window.title("Checkbox Example")

var1 = tk.IntVar()
checkbox1 = tk.Checkbutton(window, text='Option 1', variable=var1)
checkbox1.pack()

window.mainloop()

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

Create Checkboxes in Python Tkinter

In this code, we create a Tkinter window, then define an IntVar to store the state of the checkbox (1 for checked, 0 for unchecked). We create the Check button, specifying the window, label text, and associated variable. Finally, we pack the checkbox into the window and start the main event loop.

Read How to Create a Snake Game in Python Tkinter

Customize Checkbox Appearance

Tkinter provides several options to customize the appearance of checkboxes, such as:

  • background and foreground to set the colors
  • font to change the label text font
  • image to display an image next to the checkbox
  • padx and pady to add padding around the checkbox

For example, to create a checkbox with a blue background and Arial font:

checkbox1 = tk.Checkbutton(window, text='Option 1', variable=var1, 
                           background='pink', font=('Arial', 12))

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

How to Create Checkboxes in Python Tkinter

Align Multiple Checkboxes

When displaying multiple related checkboxes, it’s often helpful to align them vertically or horizontally. You can achieve this using the grid geometry manager:

checkbox1.grid(row=0, column=0, sticky='w')
checkbox2.grid(row=1, column=0, sticky='w') 

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

How to Create Checkboxes in Python Tkinter

This will arrange the checkboxes in a vertical column, aligned to the left (west) side of the cells.

Read Python Tkinter Image + Examples

Handle Checkbox Events

To make your Tkinter app interactive, you’ll want to perform actions based on the checkbox state. You can define a function to be called whenever the checkbox is toggled using the command option.

For instance, let’s say we have a checkbox for agreeing to terms and want to enable a Submit button only if the box is checked:

submit_button = tk.Button(window, text="Submit", state='disabled')

def agreement_changed():
    if var1.get() == 1:
        submit_button['state'] = 'normal'
    else:
        submit_button['state'] = 'disabled'

var1 = tk.IntVar()        
checkbox1 = tk.Checkbutton(window, text="I agree to the terms", variable=var1,
                           command=agreement_changed)

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

Create Checkboxes in Python Tkinter Handle

Now the button will enable or disable depending on the checkbox state.

Check out Python Tkinter Colors + Example

Group Related Checkboxes

In many cases, you’ll have a group of checkboxes that are related, like a list of USA states. I find it helpful to store the associated variables and checkbox objects in lists:

usa_items = ['California', 'New York', 'Texas', 'Florida', 'Illinois', 
             'Chicago', 'Los Angeles', 'San Francisco', 'Washington D.C.', 'Boston']

usa_vars = []
usa_checks = []

for i, item in enumerate(usa_items):
    var = tk.IntVar()
    usa_vars.append(var)
    cb = tk.Checkbutton(window, text=item, variable=var)
    usa_checks.append(cb)
    cb.grid(row=i, column=0, sticky='w')

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

Create Checkboxes in Python Tkinter Group Related

This makes it easy to loop through and see which options were selected:

selected_toppings = []
for i, var in enumerate(topping_vars):
    if var.get() == 1:
        selected_toppings.append(toppings[i])

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

Create Checkboxes in Python Tkinter show selected

Read Python Tkinter Autocomplete

Tkinter Check Button get Value

To get the value of a Tkinter Checkbutton, you need to associate it with a variable using the variable option. Here’s a concise example:

import tkinter as tk

def print_value():
    print(f"Checkbox value: {var.get()}")

window = tk.Tk()
window=title("Checkbox example')

var = tk.IntVar()
checkbox = tk.Checkbutton(window, text="Check me!", variable=var, command=print_value)
checkbox.pack()

window.mainloop()

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

Create Checkboxes in Python Tkinter value

In this example:

  1. We create an IntVar named var to store the state of the checkbox (1 for checked, 0 for unchecked).
  2. We create a Checkbutton and set its variable option to var. This associates the checkbox state with the IntVar.
  3. We define a function print_value() that gets called whenever the checkbox is toggled, using the command option. This function retrieves the current value of the checkbox var.get() and prints it.
  4. When you run this code and click the checkbox, it will print the current value of the checkbox (1 or 0) to the console.

So in summary, to get the value of a Tkinter Checkbutton, associate it with an IntVar using the variable option, and then call the get() method on that IntVar to retrieve the current state of the checkbox.

Read Python Tkinter Mainloop with Examples

Tkinter Check Button default value

To set a default value for a Tkinter Checkbutton, you can initialize the associated IntVar with the desired value. Here’s a concise example:

import tkinter as tk

window = tk.Tk()

var = tk.IntVar(value=1)  # Set default value to 1 (checked)
checkbox = tk.Checkbutton(window, text="Checked by default", variable=var)
checkbox.pack()

window.mainloop()

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

Create Checkboxes in Python Tkinter default

In this example:

  1. We create a IntVar named var to store the state of the checkbox.
  2. When creating var , we pass the value=1 argument to set its default value to 1, which represents the checked state. You can set it to 0 for unchecked.
  3. We create a Checkbutton and associate it with var using the variable option.
  4. Because var is initialized with a default value of 1, the checkbox will start in the checked state when the window is displayed.

Check out Python Tkinter Scrollbar – How to use

Tkinter Check Button grid

Grid is a geometry manager.

It positions widgets in a row & column format.

In this code, check buttons are created using a grid. The name provided to the check button refers to their location in row and column format.

from tkinter import *

ws = Tk()
ws.title('PythonGuides')
ws.geometry('300x250')
ws.config(bg="grey")

Checkbutton(ws, text='0, 0').grid(row=0, column=0)
Checkbutton(ws, text='0, 1').grid(row=0, column=1)
Checkbutton(ws, text='0, 2').grid(row=0, column=1)
Checkbutton(ws, text='1, 0').grid(row=1, column=0)
Checkbutton(ws, text='1, 1').grid(row=1, column=1)
Checkbutton(ws, text='1, 2').grid(row=1, column=2)
Checkbutton(ws, text='2, 0').grid(row=2, column=0)
Checkbutton(ws, text='2, 1').grid(row=2, column=1)
Checkbutton(ws, text='2, 2').grid(row=2, column=2)

ws.mainloop()

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

Create Checkboxes in Python Tkinter grid

In this output, Checkbutton with name 1,2 tells that it is situated at row first of the second column. Similarly, all the check buttons have names as per their position.

Check out Python Tkinter Scrollbar – How to use

Tkinter Check Button deselect

deselect is used to remove the check mark from the check button. If a user wants to clear the selection, in that case, deselect is used. deselect is a function & requires no argument.

In this code, multiple checkbuttons are created and these checkbuttons are set to checked by default. There is a button that can deselect all the check buttons.

from tkinter import *
 
ws = Tk() 
ws.geometry('300x250')
ws.title('Python Guides')

def clear_selection():
    cb1.deselect()
    cb2.deselect()
    cb3.deselect()
    cb4.deselect()
    cb5.deselect()
    cb6.deselect()
    
var = BooleanVar() 
var.set(True)
 
cb1 = Checkbutton(ws, text='Click me!', variable=var)
cb1.pack()
cb2 = Checkbutton(ws, text='Click me!', variable=var)
cb2.pack()
cb3 = Checkbutton(ws, text='Click me!', variable=var)
cb3.pack()
cb4 = Checkbutton(ws, text='Click me!', variable=var)
cb4.pack()
cb5 = Checkbutton(ws, text='Click me!', variable=var)
cb5.pack()
cb6 = Checkbutton(ws, text='Click me!', variable=var)
cb6.pack()

Button(ws, text='Deselect All Check buttons', command=clear_selection).pack()
 
ws.mainloop()

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

Create Checkboxes in Python Tkinter diselect

In these outputs, the first image shows the execution of the code. Whereas second image shows the deselection of check buttons when clicked. Multiple check buttons can be deselected using the function deselect.

Check out Python Tkinter Text Box Widget + Examples

Tkinter Check Button set value

To set the value of a Tkinter Checkbutton programmatically, you can use the set() method on the associated IntVar. Here’s a concise example:

import tkinter as tk

def set_checked():
    var.set(1)  # Set the value to 1 (checked)

window = tk.Tk()

var = tk.IntVar()
checkbox = tk.Checkbutton(window, text="Check me!", variable=var)
checkbox.pack()

button = tk.Button(window, text="Set Checked", command=set_checked)
button.pack()

window.mainloop()

In this example:

  1. We create an IntVar named var to store the state of the checkbox.
  2. We create a Checkbutton and associate it with var using the variable option.
  3. We define a function set_checked() that sets the value of var to 1 using the set() method. This will programmatically check the checkbox.
  4. We create a Button with the text “Set Checked” and set its command option to set_checked. This means that when the button is clicked, the set_checked() function will be called.
  5. When you run this code and click the “Set Checked” button, it will programmatically set the value of the checkbox to 1 (checked state).

Read Python Tkinter Grid

Tkinter Check Button Image Placement

Image placement can be done by setting the indicator to False. indicator on is responsible for creating a box with a check mark. setting the indicatoron to false removes the default indicator.

from tkinter import *
ws = Tk()
ws.title('PythonGudes')
ws.geometry('200x100')

def switchState():
    if cb1.get() == 1:
       disp_Lb.config(text='ON')
        
    elif cb1.get() == 0:
        disp_Lb.config(text='OFF')
    else:
        disp_Lb.config(text='error!')

switch_on = PhotoImage(width=50, height=50)
switch_off = PhotoImage(width=50, height=50)

switch_on.put(("green",), to=(0, 0, 23,23))
switch_off.put(("red",), to=(24, 0, 47, 23))
cb1 = IntVar()
Checkbutton(ws, image=switch_off, selectimage=switch_on, onvalue=1, offvalue=0, variable=cb1, indicatoron=False, command=switchState).pack(padx=20, pady=10)
disp_Lb = Label(ws)
disp_Lb.pack()
ws.mainloop()

Output:

In this output, we have displayed a Check button that can be used as a switch. This switch has 2 colours ‘red’ and ‘green’. on each click, it switches between these colors. Also, there is a message box that displays On for green color and Off for red color.

Check out Python Tkinter OptionMenu

Tkinter Check Button size

  • This is not possible to change the size of the Check button.
  • Height & width will change the position of the Checkbutton.
  • Images can be placed with the required size.
  • to know more >> check our Tkinter Checkbutton image placement section.

Read Registration form in Python using Tkinter + Login page in Python Tkinter with database SQLite3

Example: Pizza Order Form

Let’s put this all together into a more realistic example – a pizza order form that allows selecting multiple toppings and add-ons. The user can select their toppings, choose add-ons like extra cheese and delivery, and place their order.

import tkinter as tk
from tkinter import messagebox

def place_order():
    toppings = []
    for i, var in enumerate(topping_vars):
        if var.get() == 1:
            toppings.append(topping_names[i])

    if not toppings:
        messagebox.showerror('No toppings', 'Please select at least one topping.')
        return

    add_ons = []
    for i, var in enumerate(add_on_vars):
        if var.get() == 1:
            add_ons.append(add_ons_names[i]) 

    msg = f"Thank you for your order!\n\nToppings: {', '.join(toppings)}"
    if add_ons:
        msg += f"\nAdd-ons: {', '.join(add_ons)}"
    messagebox.showinfo("Order Confirmation", msg)

window = tk.Tk()
window.title("Panucci's Pizza")

# pizza topping checkboxes 
topping_label = tk.Label(window, text="Select your toppings:")
topping_label.grid(row=0, column=0, sticky='w')

topping_names = ['Pepperoni', 'Mushroom', 'Onion', 'Sausage', 'Bacon']
topping_vars = []

for i, topping in enumerate(topping_names):
    var = tk.IntVar()
    topping_vars.append(var)
    cb = tk.Checkbutton(window, text=topping, variable=var, padx=20)
    cb.grid(row=i+1, column=0, sticky='w')  

# add-ons checkboxes
add_ons_label = tk.Label(window, text="Add-ons:")
add_ons_label.grid(row=len(topping_names)+1, column=0, sticky='w', pady=(10,0))

add_ons_names = ["Extra Cheese", "Delivery"]  
add_on_vars = []

for i, item in enumerate(add_ons_names):
    var = tk.IntVar()
    add_on_vars.append(var)
    cb = tk.Checkbutton(window, text=item, variable=var) 
    cb.grid(row=len(topping_names)+2+i, column=0, sticky='w')

# place order button  
order_button = tk.Button(window, text="Place Order", command=place_order)
order_button.grid(row=len(topping_names)+len(add_ons_names)+2, column=0, pady=(10,0))

window.mainloop()

This creates a window with checkboxes for selecting pizza toppings and add-ons. When the user clicks “Place Order”, it checks which options were selected and shows an order confirmation message.

Read BMI Calculator Using Python Tkinter

Conclusion

In this tutorial, I discussed how to create checkboxes in Python Tkinter. I explained how to create a check box, align multiple checkboxes, and handle checkbox events. I also covered group related checkboxes, Tkinter Check Button get value, default value, grid, deselect, set value, image placement, button size with an example.

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.