Checkbox (Checkbutton) in Tk (tkinter)

The ttk.Checkbutton widget (available in Tk 8.5+), also known as Checkbox, is a type of button that allows two opposite states to be represented (checked/unchecked, on/off, yes/no, etc.) by the presence or absence of a check mark.

/images/checkbox-checkbutton-in-tk-tkinter/tkinter-checkbutton.gif

The following code creates a checkbox with the text "Option" as shown in the image above.

import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title("Checkbutton in Tk")
checkbutton = ttk.Checkbutton(text="Option")
checkbutton.place(x=40, y=70)
root.mainloop()

Note, however, that the widget is initialized with an indeterminate state. In order to get access to the state of a checkbox it is first necessary to create a variable that can store its value. For convenience we use tk.BooleanVar, which will represent the checked state as True and unchecked as False.

import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title("Checkbutton in Tk")
checkbutton_value = tk.BooleanVar()
checkbutton = ttk.Checkbutton(text="Option", variable=checkbutton_value)
checkbutton.place(x=40, y=70)
root.mainloop()

By default, tk.BooleanVar is initialized with False, so the widget is initially unchecked.

You can read and change a checkbutton state by using the variable's set() and get() methods, respectively. For example, the following code uses the command parameter to print the value of the checkbutton each time the widget is clicked.

import tkinter as tk
from tkinter import ttk
def checkbutton_clicked():
    print("New state:", checkbutton_value.get())
root = tk.Tk()
root.title("Checkbutton in Tk")
checkbutton_value = tk.BooleanVar()
checkbutton = ttk.Checkbutton(
    text="Option",
    variable=checkbutton_value,
    command=checkbutton_clicked
)
checkbutton.place(x=40, y=70)
root.mainloop()

If you want to initialize the widget with a checked state, set the value of the variable before creating the checkbutton:

checkbutton_value = tk.BooleanVar()
checkbutton_value.set(True)
checkbutton = ttk.Checkbutton(text="Option", variable=checkbutton_value)

Or simply:

checkbutton_value = tk.BooleanVar(value=True)
checkbutton = ttk.Checkbutton(text="Option", variable=checkbutton_value)

You can simulate a state change in the widget by using the invoke() method. A call to invoke() is similar to the user clicking on the checkbox. For example, the following code creates a button widget that changes the state of the checkbutton when clicked.

import tkinter as tk
from tkinter import ttk
def checkbutton_clicked():
    print("New state:", checkbutton_value.get())
root = tk.Tk()
root.title("Checkbutton in Tk")
checkbutton_value = tk.BooleanVar(value=True)
checkbutton = ttk.Checkbutton(
    text="Option",
    variable=checkbutton_value,
    command=checkbutton_clicked
)
checkbutton.place(x=40, y=70)
change_button = ttk.Button(text="Change state", command=checkbutton.invoke)
change_button.place(x=40, y=140)
root.mainloop()
/images/checkbox-checkbutton-in-tk-tkinter/tkinter-checkbutton-invoke.gif

The difference between calling invoke() and changing the value manually using checkbox_value.set() is that the first method completely simulates a state change, which includes the checkbox_clicked function call or that of any other registered event handler.

Wrapper Class

In most cases you'll probably want to use the following wrapper class to work with checkbuttons. In our previous code, we had to create two objects: the widget itself (checkbutton) and a variable that stores its state (checkbox_value). This wrapper class handles the tk.BooleanVar instance internally while exposing the checked() method to query the checkbutton state, and check() and uncheck() to change it.

import tkinter as tk
from tkinter import ttk
class Checkbox(ttk.Checkbutton):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.variable = tk.BooleanVar(self)
        self.config(variable=self.variable)
    def checked(self):
        return self.variable.get()
    def check(self):
        self.variable.set(True)
    def uncheck(self):
        self.variable.set(False)
def checkbox_clicked():
    print("New state:", checkbox.checked())
root = tk.Tk()
root.title("Checkbutton in Tk")
checkbox = Checkbox(text="Option", command=checkbox_clicked)
checkbox.place(x=40, y=70)
root.mainloop()

Custom State Values

A boolean variable is often used to represent the states of a checkbutton, thus checked equals to True and unchecked to False. However, you can choose any other values for those states. For example, a checkbutton instance could store its state as strings, namely "on" and "off":

# Now a string variable is used.
checkbutton_value = tk.StringVar()
checkbutton = ttk.Checkbutton(
    text="Option",
    variable=checkbutton_value,
    onvalue="on",       # Value for the checked state.
    offvalue="off"      # Value for the unchecked state.
)

Thus, checkbutton_value.get() will return one of the two values specified in the onvalue and offvalue parameters.

It is not possible to determine what value get() will return if the user has not already clicked on the checkbox, but it is certain that it will be a value other than onvalue and offvalue. In our example, we can consider:

chosen = checkbutton_value.get() in ("on", "off")

chosen will be equal to False when no choice has been made yet and True otherwise.

Comments