返回Python'Tkinter绑定函数

2024-10-03 06:23:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难弄清楚如何将“回车”键绑定到一个函数或更具体地说是一个按钮。我想将“回车”键与自我搜索功能。我有下面的代码,我尝试了许多不同的方法。现在它只是清除输入框。任何帮助都将不胜感激。在

class MainGUI:
def __init__(self, master):
    self.master = master
    master.minsize(width=500, height=175)
    master.title("Serial Number Decode")

    self.label = Label(master, text="Serial Number Decoder")
    self.label.pack()
    self.textBox=Text(master, height=1, width=30)
    self.textBox.place(relx=0.5, rely=0.1, anchor='n')
    self.textBox2=Text(master, height=2, width=50,font=("Sans",12))

    self.textBox2.place(relx=0.5, rely=0.5, anchor='s')
    self.search_button = Button(master, text="Search", command=self.search)
    self.search_button.place(relx=0.75, rely=0.15, anchor='w')

    #self.search_button.bind('<Return>', self.search)

    self.master.bind('<Return>', self.search) #Just clears the entry box

    self.multiLook_button = Button(master, text="MultiLook", command=self.multiLook)
    self.multiLook_button.place(relx=0.7, rely=0.6, anchor='w')

    self.multiSearch_button = Button(master, text="MultiSearch", command=self.multiSearch)
    self.multiSearch_button.place(relx=0.84, rely=0.6, anchor='w')

    self.close_button = Button(master, text="Close", command=master.quit)
    self.close_button.place(relx=0.85, rely=0.15, anchor='w')

Tags: textselfmastersearchplacebuttonwidthcommand
1条回答
网友
1楼 · 发布于 2024-10-03 06:23:39

假设您在类中定义了search,这样做是正确的:

class MainGUI():

    def __init__(self, master):
        # ... Code ...


    def search(self, event):
        # ... Code ...

您可以按原样访问该方法:

^{pr2}$

使用这种方法,search_button小部件必须具有焦点,以便在按下Enter时触发事件绑定。在

另外,我将建议一种不同的方式来构建你的应用程序,这将有助于增加你的代码的可读性,并允许更容易的扩展,如果你想在将来添加到应用程序。在开发一个GUI时,最好采用一种系统化的方法,即系统化的,或者一步一步的——模块化可以帮助实现这一点。在

^{3}$

需要注意的是-def search(self, event=None),这里我给event关键字参数一个默认值None,因为如果单击按钮(从设置command=self.search),一个“event”将传递给方法,但是如果方法是从绑定触发的,则“event”将被传递。另外,我在我的代码示例中并不是很彻底,我编写了一些代码,并对其进行了结构化,纯粹是为了举例,例如,我没有在GUI中注册搜索按钮,所以它不会出现,或者self.do_something没有定义,所以运行这个代码实际上会引发一个AttributeError。我希望这一切都有帮助!最后,这里是tkinter的一个很好的资源,NMT Tkinter。在

相关问题 更多 >