What is the Tkinter checkbox widget?
Tkinter is a python GUI module used to create cross-platform desktop applications. This module is easy to use and comes with python's standard library. In this answer, we'll learn to create and use checkboxes in Tkinter.
A checkbox is a button that is used to select or deselect an item from a list of options.
We can create a checkbox in Tkinter using the CheckButton widget.
Syntax
CheckButton(window, text, height, width, activebackground, activeforeground, bg, bd, command, font, padx, pady)
Parameters
window: An instance of the Tkinter window.
text: This is used to show the text for a check button option.
height: This is used to specify the height of a check button. It accepts value in terms of line numbers.
width: This is used to specify the width of a check button. It accepts value in terms of a number of characters.
activebackground: This is used to specify the background color of the check button when it is hovered by the user.
activeforeground: This is used to specify the foreground color of the check button when it is hovered by the user.
bg: This is used to provide the background color for a check button.
bd: This is used to provide the size of the border for a check button.
command: This is used to call a function when the check button state gets changed.
font: This is used to provide a font for the text present in the check button.
padx: This is used to provide the padding left and right of a check button.
pady: This is used to provide the padding top and bottom of a check button.
Let us take a look at an example of this.
Code
# Import the Tkinter library
from tkinter import *
# Create an instance of Tkinter window
window=Tk()
# Set the size of the window
window.geometry("300x300")
# Create a label widget
label=Label(window, text="Select your toppings").pack()
#Create Checkboxes
Btn1 = Checkbutton(window, text = "Olives",height = 2,width = 10)
Btn2 = Checkbutton(window, text = "Onions",height = 2,width = 10)
Btn1.pack()
Btn2.pack()
window.mainloop()Note: The above program runs on the Tkinter version
8.6
Explanation
Line 5: We create an instance of the Tkinter class
Tk()and assign it to variablewindow.Line 8: We set the size of the window as
300x300px using the methodgeometry().Line 11: We create a label using the widget
Label().Line 14–15: We create Checkboxes using the widget
CheckButton().
Free Resources