python - 键绑定命令在调用时给出不同的输出
问题描述
我有这个代码。我想要做的很简单,按回车键而不是单击按钮来获取写入条目中的文本,但是由于某种原因,当我按下回车键时出现错误,而当我按下按钮时却没有。
import tkinter as tk
from tkinter.constants import LEFT, RIGHT
class App:
count = 0
def __init__(self, root):
root.title("App")
root.geometry("300x150")
self.labell=tk.Label(root)
self.labell["justify"] = "center"
self.labell["text"] = "label"
self.labell.pack()
self.entryy=tk.Entry(root)
self.entryy.pack(side=LEFT)
self.buttonn=tk.Button(root)
self.buttonn["justify"] = "center"
self.buttonn["text"] = "Button"
self.buttonn["command"] = self.button_command
self.buttonn.pack(side=RIGHT)
# root.bind('<Return>', self.button_command)
def button_command(self, dummy):
x = self.entryy.get()
if App.count == 0:
print(x)
if __name__ == "__main__":
root = tk.Tk()
app = App(root)
root.bind("<Return>", app.button_command)
root.mainloop()
在这种情况下,我在条目“你好”中写道。
line 31, in button_command
x = self.entryy.get()
AttributeError: 'Event' object has no attribute 'entryy'
hello
另外,你们中的一些人可能已经注意到我写了bind
两次 used,我不确定将它放在哪里,如果在 if 语句中__init__
或在 if 语句中。
解决方案
我无法重现您的错误,但如果您想在bind
(使用 运行event
)和使用command=
(不使用 运行)中使用相同的函数,event
那么您应该使用默认值event
- 像event=None
-
def button_command(self, event=None):
然后它将为两者正确运行,但您不能使用它event
来获取详细信息。在使用它之前,您必须检查if event is not None:
(或)。if event:
此代码在 Linux Mint 上适用于我
我更喜欢bind
隐藏在课堂上。而self.count
不是App.count
.
我什至会躲在Tk()
课堂mainloop
里。
import tkinter as tk
class App:
def __init__(self, root):
self.count = 0
root.title("App")
root.geometry("300x150")
self.labell = tk.Label(root, text="Label", justify="center")
self.labell.pack()
self.entryy = tk.Entry(root)
self.entryy.pack(side='left')
self.buttonn = tk.Button(root, text="Button", justify="center", command=self.button_command)
self.buttonn.pack(side='right')
root.bind('<Return>', self.button_command)
def button_command(self, event=None):
x = self.entryy.get()
if self.count == 0:
print('x:', x, 'count:', self.count, 'event:', event)
if __name__ == "__main__":
root = tk.Tk()
app = App(root)
root.mainloop()
编辑:
所有访问者的信息:@serax 检查它可用于*args
解决不同数量参数的问题
def button_command(self, *args):
x = self.entryy.get()
if self.count == 0:
print('x:', x, 'count:', self.count, 'args:', args)
推荐阅读
- php - 为什么这个 pdo 获取代码没有给我我想要的
- c - 如何发送进程间消息?
- android - 在 kotlin lambda 中返回时“此处不允许返回”
- docker - Docker for Mac 和 mkdir 权限
- c++ - C++ 二进制读写文件
- ios - 如何在 iPhone 上减少使用 swift 保存的 png 大小?
- javascript - Stripe API - 成功调用 API 后在页面上打印优惠券条款
- javascript - 如何在 SVG 中的两个重叠形状上制作:悬停效果?
- javascript - 如何正确显示阵列?
- javascript - 更改 javascript 时钟中数字的样式