1

我正在使用 Tkinter 为我正在创建的简单几何计算器创建 GUI。

基本上,我拥有的是一个输入框。我想要的是程序/GUI/系统检测程序用户何时在输入框中点击“Enter”或“return”键。当检测到这一点时,我希望将条目框的内容附加到我之前定义的列表中。我还希望在显示列表内容(包括附加项)的 GUI 上创建一个简单的标签。请注意,该列表以任何内容开头。

到目前为止,这是我的代码:

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 语句中使用它的正确方法。我希望您能理解我想要寻求帮助的内容,并且我已经四处寻找我可以理解但没有成功的解释。

4

2 回答 2

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()
于 2014-04-15T10:50:46.900 回答
0

解决方案是在小部件本身上设置绑定。这样,绑定只会在焦点位于该小部件上时应用。而且由于您绑定的是特定键,因此您无需稍后检查该值。您知道用户按下了返回,因为这是唯一会导致绑定触发的事情。

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

您还有另一个问题,即您的list_add函数需要调用get变量的方法,而不是直接访问变量。但是,由于您没有使用 a 的任何特殊功能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(...)返回的结果。

于 2014-04-15T11:08:16.407 回答