c_v=tk.BooleanVar(master,value,name)
master
: (Optional)The variable is associated with, default value is parent window.value
:(Optional) We can set the initial value for the variable. name
: (Optional) Name given default is PY_VAR1
trace_add(self, mode, callback)
For an BooleanVar() we can check the different modes of this variable and trigger call back functions. This is the main advantage of using such variables.
db1.trace_add(['write','read'],my_r) # callback when data changes
b1 = tk.Button(my_w,text='Update',command=lambda:bv1.set(True))
This triggers the trace_add() which used the callback function my_r() to print the value of the variable ( True ) to our console.
import tkinter as tk
from tkinter import *
my_w = tk.Tk()
my_w.geometry("300x100") # Size of the window
my_w.title("www.plus2net.com") # Adding a title
def my_r(*args):
print(bv1.get()) # Print when variable changes.
bv1 = tk.BooleanVar(my_w) # declare Boolean Variable
bv1.set(0)
b1 = tk.Button(my_w,text='Update',command=lambda:bv1.set(1))
b1.grid(row=2,column=3,padx=30,pady=10)
bv1.trace_add('write',my_r) # monitor the change of variable
my_w.mainloop()
Output
True
Use StringVar() for handling String data bv1.set(1) # assign value to bv1
print(bv1.get()) # display the value assigned to bv1
bv1=tk.BooleanVar(value=True) # Assign value to bv1
print(len(str(bv1.get()))) # 4
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("400x200") # Size of the window
c_v=tk.BooleanVar()# Declaring the Boolean variable
c_v.set(1) # Set the value to 2
c1=tk.Checkbutton(my_w,text='I Agree',variable=c_v,
onvalue=1,offvalue=0,font=20)
c1.grid(row=0,column=0,padx=15,pady=15)
l1=tk.Label(my_w,text='Output',font=22,bg='yellow')
l1.grid(row=1,column=0,padx=15,sticky='ew')
def my_upd(*args):
my_data=c_v.get() # read the value or state of the Checkbutton
l1.config(text=str(my_data)) # Update the Label with data
c_v.trace_add('write',my_upd) # On change of Boolean variable trigger function
my_upd() # Update function
my_w.mainloop() # Keep the window open
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.