Search code examples
pythontkinter

how to wait user type finish in entry widget from tkinter only execute bind function


I try search in stack overflow but I cant get the answer I need. Below is the code:

from tkinter import *

root = Tk()

text = StringVar()
entry = Entry(root, textvariable=text)
entry.grid(row=0, column=0)

def show(*args):
    print(text.get())

text.trace_add("write", show)

root.mainloop()

I am looking for user to type finish in the entry widget and only auto trigger the show functions. Instead of this output:

enter image description here

i am looking for this output:

enter image description here

Please help.

Edit: My show function contains below code:

enter image description here


Solution

  • You can use .after() to execute show() in the callback of trace_add() as below:

    from tkinter import *
    
    root = Tk()
    
    text = StringVar()
    entry = Entry(root, textvariable=text)
    entry.grid(row=0, column=0)
    
    scheduler = None
    
    def show():
        print(text.get())
    
    def on_change(*args):
        global scheduler
        # cancel scheduler upon content change
        if scheduler:
            entry.after_cancel(scheduler)
        # create new scheduler to execute show one second later
        # change 1000 (ms) to whatever value you want
        scheduler = entry.after(1000, show)
    
    text.trace_add('write', on_change)
    
    root.mainloop()