Marciel Fonseca
Marciel Fonseca

Reputation: 381

How to listen to any Entry change events?

I'm writing a little program that populates values that come from an API every second into Entry components. But also I need for the user to be able to change any of the values anytime by themselves. So what I have right now is:

from tkinter import *

root = Tk()
sv = StringVar()

def callback():
    print(sv.get())
    return True

e = Entry(root, textvariable=sv, validate="key", validatecommand=callback)
e.grid()
e = Entry(root)
e.grid()
root.mainloop()

This way I can activate my callback function whenever they press a key. However, I need it to happen also when the value is changed by the API ticker that changes the Entry components. I need my function to be called whenever any Entry text/value is changed on any Entry. I used to code in Delphi and there we had an onChage event for edits, but in Python I'm a little lost.

Upvotes: 1

Views: 459

Answers (1)

Henry Yik
Henry Yik

Reputation: 22493

You can use the trace method on your StringVar:

def trace_method(*args):
    #do your thing...

sv.trace("w",trace_method)

If you need to pass a parameter, you can use lambda:

def trace_method(*args,parameter=None):
    if parameter:
        print (parameter)

sv.trace("w",lambda *args: trace_method(parameter="Something"))

Upvotes: 3

Related Questions