Search code examples
pythoneventstkintertkinter-entry

Tkinter Entry/Text widget problem when I use bind function


I'm new to Tkinter, I want to print Entry's contents while I'm typing. Here's my code I've tried:

from tkinter import *


def get_(e):
    print(entry.get())

root = Tk()
entry = Entry(root)
entry.pack()

entry.bind("<KeyPress>", get_)

mainloop()

But it seems not "synchronous"(when I type "123" in, output only is "12" and so on)

The following code works properly, but I don't know why:

from tkinter import *


def get_(e):
    print(entry.get())

root = Tk()
entry = Entry(root)
entry.pack()

root.bind("<KeyPress>", get_)
## or this: entry.bind("<KeyRelease>", get_)
## or this: entry.bind_all("<KeyPress>", get_)

mainloop()

is there some weird rule I don't know about? Any and all help would be wonderful, thanks in advance!


Solution

  • Question: entry.bind("<KeyPress>" seems not "synchronous" (when I type "123" in output only is "12" and so on ...), while root.bind("<KeyPress>" works.

    The event entry.bind("<KeyPress>", ... get fired before the value in tk.Entry is updated. This explains why the output is allways one char behind.

    The event root.bind("<KeyPress>", ... get fired after the value in tk.Entry is updated. This explains why this is working.

    Alternatives:


    Reference: