在Tkinter中检查用户在输入框中按下'Enter'键

1 投票
2 回答
745 浏览
提问于 2025-04-18 02:48

我正在使用Tkinter来创建一个简单的几何计算器的图形界面。

简单来说,我有一个输入框(Entry box)。我希望程序能够检测到用户在输入框中按下“回车”键(Enter或Return)。一旦检测到这个动作,我想把输入框里的内容添加到我之前定义的一个列表中。同时,我还希望在图形界面上显示一个简单的标签,来展示这个列表的内容(包括新添加的项目)。需要注意的是,这个列表一开始是空的。

这是我目前的代码:

from tkinter import *
#Window setup(ignore this)
app = Tk()
app.title('Geometry Calculator')
app.geometry('384x192+491+216')
app.iconbitmap('Geo.ico')
app.minsize(width=256, height=96)
app.maxsize(width=384, height=192)
app.configure(bg='WhiteSmoke')
#This is the emtry list...
PointList = []
#Here is where I define the variable that I will be appending to the list (which is the              object of the Entry box below)
StrPoint = StringVar()
def list_add(event):
#I don't really know how the bind-checking works and how I would implement it; I want to check if the user hits enter while in the Entry box here
    if event.char == '':
        PointList.append(StrPoint)
e1 = Entry(textvariable=StrPoint).grid(row=0, column=0)
app.bind('<Return>', list_add)

mainloop()

我其实不太清楚怎么正确地检查“回车”键,然后在if语句中使用它。我希望你能理解我想要的帮助,我已经到处找过解释,但都没有找到我能理解的。

2 个回答

0

解决这个问题的方法是直接在小部件上设置绑定。这样一来,绑定只会在这个小部件获得焦点时生效。而且因为你绑定的是特定的按键,所以之后就不需要再检查值了。你知道用户按下了回车键,因为只有这个操作会触发绑定。

...
e1.bind('<Return>', list_add)
...

你还有一个问题,就是你的 list_add 函数需要调用变量的 get 方法,而不是直接访问这个变量。不过,由于你并没有使用 StringVar 的任何特殊功能,其实你并不需要它——这只是多了一件需要管理的事情。

下面是如何在不使用 StringVar 的情况下做到这一点:

def list_add(event):
    PointLit.append(e1.get())
...
e1 = Entry(app)
e1.grid(row=0, column=0)
e1.bind('<Return>', list_add)

注意,你需要分两步来创建小部件并布局小部件。如果像你之前那样做(e1=Entry(...).grid(...)),会导致 e1 的值变成 None,因为 .grid(...) 返回的就是这个。

0

与其把它绑定到app,不如直接把它绑定到Entry这个控件对象,也就是e1

from tkinter import *
#Window setup(ignore this)
app = Tk()
app.title('Geometry Calculator')
app.geometry('384x192+491+216')
app.iconbitmap('Geo.ico')
app.minsize(width=256, height=96)
app.maxsize(width=384, height=192)
app.configure(bg='WhiteSmoke')
#This is the emtry list...
PointList = []
#Here is where I define the variable that I will be appending to the list (which is the              object of the Entry box below)
StrPoint = StringVar()
def list_add(event):
    print ("hello")
#I don't really know how the bind-checking works and how I would implement it; I want to check if the user hits enter while in the Entry box here
    if event.char == '':
        PointList.append(StrPoint)
e1 = Entry(textvariable=StrPoint)
e1.grid(row=0, column=0)#use grid in next line,else it would return None
e1.bind('<Return>', list_add)# bind Entry

mainloop()

撰写回答