
str1.trace_add('write',my_bg) # trigger when varaible changes
More about StringVar()
def my_bg(*args):
x=len(str1.get()) # Number of chars entered
str2.set(x) # Display the number ( value of x)
if(x<=3): # check value of x
e1.config(bg='red')
elif(x<=6):
e1.config(bg='yellow')
elif(x<=9):
e1.config(bg='lightgreen')

import tkinter as tk
my_w = tk.Tk()
my_w.geometry("400x200") # Size of the window
my_w.title("www.plus2net.com") # Adding a title
font1 = ("Times", 26, "normal") # increase the font size and style
def my_bg(*args):
x = len(str1.get()) # Number of chars entered
str2.set(x) # Display the number (value of x)
if(x <= 3): # check value of x
e1.config(bg="red")
elif(x <= 6):
e1.config(bg="yellow")
elif(x <= 9):
e1.config(bg="lightgreen")
str1 = tk.StringVar(my_w) # declare StringVar()
str2 = tk.StringVar() # to show number of chars entered
l1 = tk.Label(my_w, textvariable=str2, width=5, font=font1)
l1.grid(row=0, column=0) # show the number of chars entered
e1 = tk.Entry(my_w, textvariable=str1, font=font1, width=10)
e1.grid(row=0, column=1, pady=20)
# str1.trace('w', my_bg) # trace is deprecated
str1.trace_add('write', my_bg) # trigger when variable changes
my_w.mainloop()
Tkinter Entry Show Hide Password Using Checkbutton
Tkinter Text
How to Validate user entered data
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.