python - 如何在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()
我想让我的代码在我按下按钮时以及当我在焦点位于按钮上时按下输入键时都破坏窗口。
我怎样才能做到?
解决方案
使用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
推荐阅读
- node.js - 如何在nodejs中不使用每个循环或任何循环直接访问数据?
- wordpress - 禁用 WordPress 5.5 插件电子邮件
- amazon-web-services - 气流的中央电子邮件通知
- typescript - 从函数返回的 TypeScript 'string'
- angular - 角材料模块会自动摇树吗?
- python - 使用 python 记录为 JSON 行
- javascript - 除了 .innerHTML 之外,还有哪些其他选项可以将 Javascript 生成的 HTML 插入 DOM?
- html - 减小容器高度时将元素放入其容器中
- node.js - 地图列表在 DynamoDB 查询中返回未定义
- javascript - 仅 forEach 必填字段