Python tkinter IntVar() trace

For an IntVar() so we can check the different modes of this variable, like this

r :Read - the variable is read by someone
w :Write- the variable is written by someone.
u :undefined – The variable is deleted

Here is an example which uses w ( write ) mode to display the value of the variable when ever it changes.
We used one Button and used on Click event to change the value of this variable db1 from 5 to 10.
b1 = tk.Button(my_w,text='Update',command=lambda:db1.set(10))
This triggers the trace() 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("")  # Adding a title

def my_r(*args):
    print(int1.get()) #  Print when variable changes.
int1 = tk.IntVar(my_w) # declare IntVar()

b1 = tk.Button(my_w,text='Update',command=lambda:int1.set(10))  

int1.trace('w',my_r) # monitor the change of variable
Use StringVar() for handling String data
Use DoubleVar() for handling Float Data

set() and get() methods of IntVar

In above examples we used set() method to assign data to the Integer variable and to read the data stored we used get() method. These two methods are frequently used in our scripts.
int1.set(10) # assign value to int1
print(int1.get()) # display the value assigned to int1

Initializing IntVar

We can using set() method to assign data to IntVar, after declaring or we can assign value while declaring the string variable.
int1=tk.IntVar(value=5) # Assign value to int1

Length of IntVar

Before using len function, we have to convert the IntVar to string by using str()

Normal Variable and IntVar

IntVar() is a class in Tkinter. In a GUI application we require various events to be captured to trigger different functions (requirements). If we use normal Python variable with widgets then monitoring the changes is difficult. However by using a IntVar we can monitor the changes and trigger functions based on the requirements.

StringVar() DoubleVar() BooleanVar()
Subscribe to our YouTube Channel here


* indicates required
Subscribe to plus2net

    Post your comments , suggestion , error , requirements etc here

    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2022 All rights reserved worldwide Privacy Policy Disclaimer