检查用户是否按下“返回”按钮。在条目框中选择Tkinter

时间:2014-04-15 10:42:44

标签: python user-interface tkinter bind tkinter-entry

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

基本上,我所拥有的是一个输入框。我想要的是程序/ GUI /系统检测程序的用户何时点击'输入'或者'返回'键,他们在输入框中。当检测到这一点时,我希望将Entry框的内容附加到我之前定义的列表中。我还想在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语句中使用它。 我希望你能理解我试图获得帮助的东西,并且我已经四处寻找可以理解但没有成功的解释。

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分:0)

解决方案是在小部件本身上设置绑定。这样,绑定仅适用于焦点在该窗口小部件上。由于您对特定密钥具有约束力,因此您不需要稍后检查该值。你知道用户按下了return,因为这是导致绑定触发的唯一因素。

...
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(...)返回的内容。