当我使用绑定功能时 Tkinter Entry/Text 小部件问题

Tkinter Entry/Text widget problem when I use bind function

我是 Tkinter 新手,我想在输入时打印 Entry 的内容。 这是我试过的代码:

from tkinter import *


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

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

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

mainloop()

但好像不是"synchronous"(当我输入“123”时,输出只有“12”等等)

以下代码可以正常运行,但我不知道为什么:

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()

有什么我不知道的奇怪规则吗?任何和所有帮助都会很棒,提前致谢!

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

事件 entry.bind("<KeyPress>", ... 被触发 tk.Entry 中的值被更新之前。这解释了为什么输出总是 one 字符落后。

事件 root.bind("<KeyPress>", ... 被触发 tk.Entry 中的值更新后。这解释了为什么这是有效的。

备选方案:

  • 使用"<KeyRelease>"事件
  • tkinter-variable-trace-method

参考: