In this post we will see Checkbox in the tkinter. We will see how to use them as well as how to get input from them when they are checked and unchecked. Lets get started,
IN[1]
import tkinter as tk
from tkinter import ttk
try :
from ctypes import windll
windll.shchore.SetProcessDpiAwareness(1)
except :
pass
root = tk.Tk()
root.title("Checkboxes")
root.geometry("400x50")
selected_option = tk.StringVar()
def print_current_option():
print(selected_option.get())
c1 = ttk.Checkbutton(
root,
variable=selected_option,
command=print_current_option,
onvalue="on",
offvalue="off",
text = "Tomato"
).pack()
root.mainloop()
OUT[1]
We can use the class Checkbutton to create the Checkbox widget and pack to place them. This Checkbutton class has the following arguments. Check below to know their properties.
onvalue : The value to be sent when checkbox is checked.
offvalue : The value to be sent when checkbox is unchecked.
text : The string to be displayed beside the square.
command : Function to be called when an event is occurred on the widgets.
variable : Get and store the on and off value from the variable when checked and unchecked.
In the above program when the box is checked the onvalue "ok" is saved in the variable. Since clicking is the event performed the value store in the variable will be printed. Similarity for uncheck action offvalue is stored in the variable which will be printed in the console.