We use the get() method of string variable str1 to read the string entered by the user and then used len() function to calculate the number of chars in the user entered string ( variable x ) .
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')
Full code is here
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 styledef 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()