How to display the updated text value without erasing the label text in python tkinter?

Question:

I am new to tkinter. I have tried the below program. It’s working fine. Is there any way I can get the number of character without erasing the label text?

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
Generator = tk.Frame(my_w)
Generator.pack(padx=10, pady=10, fill='x', expand=True)
e1_str=tk.StringVar()

e1_str=tk.StringVar() # declaring a StringVar()
e1 = tk.Entry(Generator,textvariable=e1_str,bg='yellow',font=28) # Entry box
e1.pack(padx=0,fill='x', expand=True)

l1 = tk.Label(Generator,  text='No of Chars here' ,font=28)  # added one Label 
l1.pack(padx=0,fill='x', expand=True)
def my_upd(*args):
    l1.config(text=str(len(e1_str.get()))) # read & assign text to StringVar()

e1_str.trace('w',my_upd) # triggers on change of StringVar
my_w.mainloop()
Asked By: thangaraj1980

||

Answers:

You get number of characters by e1_str.get()

For example you could modify your function:

def my_upd(*args):
    t = e1_str.get()
    if t:
        l1.config(text='Number of Chars here: ' + str(len(t)))
    else:
        l1.config(text='No of Chars here')
Answered By: Evgeny Romensky

Update text property in your label to: f'No of Chars here: {len(e1_str.get())}':

import tkinter as tk

my_w = tk.Tk()
my_w.geometry("400x150")
my_w.title("plus2net.com")
Generator = tk.Frame(my_w)
Generator.pack(padx=10, pady=10, fill='x', expand=True)
e1_str = tk.StringVar()
e1 = tk.Entry(Generator, textvariable=e1_str, bg='yellow', font=28)
e1.pack(padx=0, fill='x', expand=True)
l1 = tk.Label(Generator, text='No of Chars here', font=28)
l1.pack(padx=0, fill='x', expand=True)


def my_upd(*args):
    l1.config(text=f'No of Chars here: {len(e1_str.get())}')


e1_str.trace('w', my_upd)  # triggers on change of StringVar
my_w.mainloop()

Output:

enter image description here

Answered By: Alderven
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.