key-bind命令在调用时提供不同的输出

thtygnil  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(266)

我有这个密码。我想做的很简单,按return键而不是单击按钮来获取条目中写入的文本,但由于某种原因,当我按enter键时会出现错误,而当我按按钮时不会出现错误。

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()

在本例中,我在条目“hello”中写道。

line 31, in button_command
    x = self.entryy.get()
AttributeError: 'Event' object has no attribute 'entryy'
hello

另外,正如你们中的一些人可能已经注意到的,我用 bind 有两次,我不知道把它放在哪里,如果在 __init__ 或者在if语句中。

cqoc49vn

cqoc49vn1#

我无法重现您的错误,但如果您想在中使用相同的函数 bind (哪一个运行它 event )和 command= (它运行时没有 event )然后,您应该使用默认值 event -像 event=None -

def button_command(self, event=None):

然后,它将为这两个应用程序正确运行,但您不能使用 event 来获取详细信息。你得检查一下 if event is not None: (或 if event: )在使用它之前。
这段代码在LinuxMint上适用
我更喜欢 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()

相关问题