Tkinter,Entry 小部件,是否可以检测输入文本?
我在一个简单的计算器上有一个 Entry 小部件.用户可以选择通过键盘输入方程式.我想知道是否有一种方法可以检测到输入到 Entry 小部件中的字符(在我的情况下来自键盘).所以,焦点在小部件上,用户按下4",它出现在小部件上......我可以检测到这种行为,以记录输入的基本目的吗?
I have an Entry widget on a simple calculator. The user can choose to enter an equation via the keypad. I was wondering if there was a way to detect a character(from the keypad in my case) being typed into the Entry widget. So, focus is on the widget, user presses '4', it comes up on the widget... can I detect this act, for basic purposes of logging the input?
每次在 Tkinter 窗口内按下一个键,都会创建一个 Tkinter.Event
实例.您需要做的就是访问该实例.这是一个简单的脚本,演示了如何:
Every time you press a key inside a Tkinter window, a Tkinter.Event
instance is created. All you need to do is access that instance. Here is a simple script that demonstrates just how:
from Tkinter import Tk, Entry
root = Tk()
def click(key):
# print the key that was pressed
print key.char
entry = Entry()
entry.grid()
# Bind entry to any keypress
entry.bind("<Key>", click)
root.mainloop()
key
(作为一个 Tkinter.Event
实例)包含许多不同的属性,可用于在按下的键上获取几乎任何类型的数据.我选择在这里使用 .char
属性,这将使脚本打印每个按键是什么.
key
(being a Tkinter.Event
instance) contains many different attributes that can be used to get almost any type of data you want on the key that was pressed. I chose to use the .char
attribute here, which will have the script print what each keypress is.