r_v=tk.IntVar(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 IntVar() 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:db1.set(10))
This triggers the trace_add() which used the callback function my_r() to print the value of the variable ( 10 ) 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(int1.get()) # Print when variable changes.
int1 = tk.IntVar(my_w) # declare IntVar()
int1.set(5)
b1 = tk.Button(my_w,text='Update',command=lambda:int1.set(10))
b1.grid(row=2,column=3,padx=30,pady=10)
int1.trace_add('write',my_r) # monitor the change of variable
my_w.mainloop()
Output
10
Use StringVar() for handling String data int1.set(10) # assign value to int1
print(int1.get()) # display the value assigned to int1
int1=tk.IntVar(value=5) # Assign value to int1
print(len(str(int1.get())))
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("400x200") # Size of the window
r_v=tk.IntVar() # Declaring the integer variable
r_v.set(2) # Set the value of IntVar to 2
r1=tk.Radiobutton(my_w,text='One',value=1,variable=r_v,font=20)
r1.grid(row=0,column=0,padx=15,pady=15)
r2=tk.Radiobutton(my_w,text='Two',value=2,variable=r_v,font=20)
r2.grid(row=0,column=1,padx=15,pady=15)
r3=tk.Radiobutton(my_w,text='Three',value=3,variable=r_v,font=20)
r3.grid(row=0,column=2,pady=15)
l1=tk.Label(my_w,text='Output',font=22,bg='yellow')
l1.grid(row=1,column=0,columnspan=3,sticky='ew')
def my_upd(*args):
my_data=r_v.get() # read the value of selected radio button
l1.config(text=str(my_data)) # Update the Label with data
r_v.trace_add('write',my_upd) # call the my_upd() once data is changed.
my_upd() # Update function
my_w.mainloop() # Keep the window open
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.