StringVar() 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 StringVar we can monitor the changes and trigger functions based on the requirements.
Example : Declare the password is strong or weak based on the number of chars entered by user. Here we can use StringVar and each time the variable changes its stored data, we can trigger the function checking the length of the input and show the message.
More Examples on StringVar()
The most frequently used method is trace(), by using this we can track the changes and trigger function. Here are some scripts using trace() method of StringVar().
Counting the number of chars
As we enter data inside the entry box, the total number of chars entered will be displayed by the side ( Labell1 ) . Here StringVar() e1_str is connected to Entry widgete1 using textvariable option.
The trace() method of e1_str is used to trigger the function my_upd() whenever the e1_str data changes.
Inside the function my_upd() we read the user input by using e1.get() , then found out the number of chars by using len() and the converted the integer to string by using str() function.
import tkinter as tk
my_w = tk.Tk()
from tkinter import *
my_w.geometry("400x150") # Size of the window width x height
my_w.title("plus2net.com") # Adding a title
e1_str=tk.StringVar() # declaring a StringVar()
e1 = tk.Entry(my_w,textvariable=e1_str,bg='yellow',font=28) # Entry box
l1 = tk.Label(my_w, text='No of Chars here' ,font=28) # added one Label
l1.config(text=str(len(e1_str.get()))) # read & assign text to StringVar()
e1_str.trace('w',my_upd) # triggers on change of StringVar