Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to get the input from a Checkbox in Python Tkinter?
A checkbox widget in Python Tkinter is an input widget that represents a boolean state - either checked (True) or unchecked (False). Checkboxes are commonly used in GUI applications where users need to select one or more options from a list.
To get the input value from a checkbox, we use the get() method on the variable associated with the checkbox. This method returns the current state of the checkbox.
Basic Checkbox Example
Here's how to create checkboxes and retrieve their values ?
# Import Tkinter library
from tkinter import *
# Create an instance of tkinter frame
win = Tk()
# Set the geometry of Tkinter frame
win.geometry("700x250")
# Define Function to print the input value
def display_input():
print("Input for Python:", var1.get())
print("Input for C++:", var2.get())
# Define empty variables
var1 = IntVar()
var2 = IntVar()
# Define checkboxes
t1 = Checkbutton(win, text="Python", variable=var1, onvalue=1, offvalue=0, command=display_input)
t1.pack()
t2 = Checkbutton(win, text="C++", variable=var2, onvalue=1, offvalue=0, command=display_input)
t2.pack()
win.mainloop()
Output
When you run this code, a window appears with two checkboxes. Clicking on them will print their current state to the console ?
Input for Python: 1 Input for C++: 0
Using BooleanVar for True/False Values
Instead of IntVar, you can use BooleanVar to get boolean values directly ?
from tkinter import *
win = Tk()
win.geometry("400x200")
# Using BooleanVar for True/False values
python_var = BooleanVar()
cpp_var = BooleanVar()
def show_selection():
print("Python selected:", python_var.get())
print("C++ selected:", cpp_var.get())
# Create checkboxes with BooleanVar
Checkbutton(win, text="Python", variable=python_var, command=show_selection).pack()
Checkbutton(win, text="C++", variable=cpp_var, command=show_selection).pack()
Button(win, text="Show Selection", command=show_selection).pack(pady=10)
win.mainloop()
Key Parameters
| Parameter | Description | Example |
|---|---|---|
variable |
Variable to store checkbox state | IntVar(), BooleanVar() |
onvalue |
Value when checked | 1, True |
offvalue |
Value when unchecked | 0, False |
command |
Function to call when clicked | callback_function |
Conclusion
Use the get() method on the checkbox variable to retrieve its current state. BooleanVar provides True/False values while IntVar gives numeric values (0/1).
