首页 > 解决方案 > 如何在python中绑定按下按钮并按下回车键?

问题描述

我想绑定按下按钮并按下回车键。

我正在使用 Python 3。

这是我的代码:

class MakeaButton(object):
    def sizedButton(self, root, x, y):
        f = Frame(self.root, width = 100, height = 35)
        f.pack_propagate(0)
        f.place(x = x, y = y)

        self.btn = Button(f, text = 'Button', command = self.destroy)
        self.btn.pack(fill = BOTH, expand = 1)

    def background(self):
        def close_onclick():
            sys.exit()

        self.root = Tk()
        self.root.geometry('1160x640')

        self.sizedButton(self.root, 530, 450)

        self.root.mainloop()

    def destroy(self):
        self.root.destroy()

我想让我的代码在我按下按钮时以及当我在焦点位于按钮上时按下输入键时都破坏窗口。

我怎样才能做到?

标签: pythonpython-3.xtkinter

解决方案


使用bind()

def sizedButton(self, root, x, y):
    f = Frame(self.root, width = 100, height = 35)
    f.pack_propagate(0)
    f.place(x = x, y = y)

    self.btn = Button(f, text = 'Button', command = self.destroy)
    self.btn.pack(fill = BOTH, expand = 1)
    self.btn.bind("<Button-1>", lambda e, b: self.destroy()) # for click
    self.btn.bind("<Return>", lambda e, b: self.destroy()) # for return

推荐阅读