Python tkinter StringVar() trace

For an StringVar() 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

StringVar()
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 str1 from Hello to Welcome.
b1 = tk.Button(my_w,text='Update'command=lambda:str1.set('Welcome') )
This triggers the trace() which used the callback function my_r() to print the value of the variable ( Welcome ) to our console.
import tkinter as tk
from tkinter import *
my_w = tk.Tk()
my_w.geometry("300x200")  # Size of the window 
my_w.title("www.plus2net.com")  # Adding a title

def my_r(*args):
    print(str1.get()) #  Print when variable changes.
	
str1 = tk.StringVar(my_w) # declare StringVar()
str1.set('Hello') 

l3 = tk.Label(my_w,  textvariable=str, width=15 )  
l3.grid(row=2,column=1)

b1 = tk.Button(my_w,text='Update',command=lambda:str1.set('Welcome'))  
b1.grid(row=2,column=3)

str1.trace('w',my_r)

my_w.mainloop() 
Output
Welcome

Length of StringVar

We can use len
len(str1.get())

Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    22-03-2021

    Very bad to call a variable in Python "str"
    str = tk.StringVar(my_w) # declare StringVar()
    because str is build-in method to stringify data!
    class str(object='') --> built-in function in Python

    23-03-2021

    Thanks, Let us use str1

    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-2021 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer