Search code examples
pythontkinterreal-time-data

Getting real time data in Tkinter


Consider the code below:

from tkinter import *

screen = Tk()

e =Entry()
e.pack()


screen.mainloop()

Now how to get to display the length of the characters entered in the e entry widget in real-time? It doesn't matter if the data is displayed in the GUI or Corresponding terminal


Solution

  • There are atleast 3 ways to do this here with one being better than the other:

    • Using trace from StringVar:
    def func(*args):
        print(len(var.get()))
    
    var = StringVar()
    
    e = Entry(screen,textvariable=var)
    e.pack()
    
    var.trace('w',func)
    

    Every time the value of var is changed, func will be called.

    • Using bind to each key release:
    def func(*args):
        print(len(e.get()))
    
    e.bind('<KeyRelease>',func)
    
    • Using after(ms,func) to keep repeating the function:
    def func():
        print(len(e.get()))
        screen.after(500,func)
    
    func()
    

    As you can see, the first method is more efficient as it does not unnecessarily prints out values when you select all the items(with Ctrl+A) and so on. Using after() will be the most ridiculous method as it will keep printing the length always as there are no restrictions provided.