【问题标题】:"instance has no attribute button" when accessing a variable defined in __init__ [duplicate]访问__init__中定义的变量时“实例没有属性按钮” [重复]
【发布时间】:2016-09-08 14:58:59
【问题描述】:

我是 tkinter 的新手,似乎无法理解 oop,我认为这就是问题所在。

这是我的代码:

from Tkinter import *
from PIL import ImageTk, Image

images = {
    "first" : "miog.png",
    "combat" : "mio kicking ass.jpg"
    }

class App:

    def __init__(self, master, image_dict):
        frame = Frame(master)
        frame.pack()

        self.pic = ImageTk.PhotoImage(Image.open(image_dict["first"]))
        self.image = Label(frame, image = self.pic)
        self.image.pack(side = TOP)

        self.button = Button(frame, text="Start", command=self.combat())
        self.button.pack(side = RIGHT)

    def combat(self):
        self.button.destroy()

window = Tk()
window.title("aaa")

app = App(window, images)

window.mainloop()

我从控制台得到的错误是:

AttributeError: App instance has no attribute 'button'

我不明白,在初始化实例时(在 init 中)不是按钮吗?

我为类似问题找到的所有其他答案都与缩进有关,但我确保仔细检查所有内容(所有选项卡以及我认为它们应该在的所有位置)。

【问题讨论】:

    标签: python python-2.7 tkinter


    【解决方案1】:

    您需要将 callable 传递给按钮实例,而不是结果。

    self.button = Button(frame, text="Start", command=self.combat)
    

    否则你会立即调用它,所以它会在按钮实际定义之前执行。

    【讨论】:

    • 我想我明白了。基本上它在创建 self.button 并将按钮分配给 self.button 之前运行 self.combat()?不过很奇怪,因为我认为直到我点击按钮命令才会运行......
    • 如果你传递我上面显示的可调用对象,它不会。但除此之外,它只是标准的 Python 评估规则;在执行左手之前,必须先计算右手边的所有内容。
    • 哦...我没有看到 self.combat 之后缺少括号,所以我认为您重写了错误的代码部分。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2012-06-15
    • 2022-06-26
    • 2023-03-17
    • 2011-10-26
    • 2018-06-21
    • 2013-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多