Configure Background based on Number of Chars

Change in background colour using config()

Managing background colour of Tkinter Entry based on number of chars entered by user using config()


trace() method

Our string variable str1 trace() method triggers the callback function my_bg() when the value of str1 changes.
str1.trace('w',my_bg) # trigger when varaible changes 
More about StringVar()

Function my_bg()

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 ) .

We used one if elif code block to configure the background colour of the Entry box.
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')
Change in background colour based on Number of chars entered in Tkinter

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 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 varaible changes 

my_w.mainloop() 
Tkinter Entry Show Hide Password Using Checkbutton Tkinter Text How to Validate user entered data
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



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