2

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!

3
  • While not an exact duplicate, this has all the information you need: stackoverflow.com/questions/11541262/… Commented Dec 27, 2019 at 7:38
  • @BryanOakley Thanks for your comment. I read your answer and code. So what bind tag like "Entry" does is insert some characters into the widget. Am I right? Commented Dec 27, 2019 at 8:28
  • @Darcy: "print Entry's contents while I'm typing": You want tkinter-variable-trace-method Commented Dec 27, 2019 at 9:49

1 Answer 1

2

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:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.