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!

stovfl
  • 14,998
  • 7
  • 24
  • 51
Darcy
  • 160
  • 1
  • 9
  • While not an exact duplicate, this has all the information you need: https://stackoverflow.com/questions/11541262/basic-query-regarding-bindtags-in-tkinter/11542200#11542200 – Bryan Oakley Dec 27 '19 at 07: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? – Darcy Dec 27 '19 at 08:28
  • @Darcy: ***"print Entry's contents while I'm typing"***: You want [tkinter-variable-trace-method](https://stackoverflow.com/questions/17131826/tkinter-variable-trace-method) – stovfl Dec 27 '19 at 09:49

1 Answers1

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:

stovfl
  • 14,998
  • 7
  • 24
  • 51