首页 > 解决方案 > 键绑定命令在调用时给出不同的输出

问题描述

我有这个代码。我想要做的很简单,按回车键而不是单击按钮来获取写入条目中的文本,但是由于某种原因,当我按下回车键时出现错误,而当我按下按钮时却没有。

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 语句中。

标签: pythonclasstkinter

解决方案


我无法重现您的错误,但如果您想在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)

推荐阅读