AttributeError:''对象没有属性'' - 尝试在tkinter中隐藏/显示元素

时间:2017-06-21 15:20:17

标签: python tkinter

我现在已经为此奋斗了3天,但我似乎无法掌握这一点。很简单,当我按下保存按钮时,我试图显示(打包)取消按钮,但它根本不起作用。

当我按下保存按钮时,我得到:

AttributeError: 'MainWindow' object has no attribute 'cancelButton'

我不确定为什么会这样,我可以清楚地看到cancelButton对象就在那里。我已经阅读过如何在单击按钮之前无法初始化或调用对象,但是再次,不知道这是怎么回事,因为我在屏幕上看到对象,我可以单击第一个按钮。

为了记录,我尝试按照此处发布的教程In Tkinter is there any way to make a widget not visible? 进行操作,但是当我尝试将此示例合并到我的代码中时,我的代码结构完全不同,I&#39 ; m留下了上面的错误。

我的代码如下,如果有人可以帮助解释发生了什么。

    from tkinter import *
from PIL import Image, ImageTk

class MainWindow(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("Hello World")

        toolbar = Frame(self.parent, bd=1, relief=RAISED)

        self.img = Image.open("Icons\save.png")
        eimg = ImageTk.PhotoImage(self.img)
        saveButton = Button(toolbar, text="Save ", image=eimg, compound="left", relief=RAISED, command=self.show_toolbar)
        saveButton.image = eimg
        saveButton.pack(side=LEFT, padx=2, pady=2)

        self.img = Image.open("Icons\cancel.png")
        eimg = ImageTk.PhotoImage(self.img)
        cancelButton = Button(toolbar, text="Cancel ", image=eimg, compound="left", relief=RAISED, command=self.quit)
        cancelButton.image = eimg

        toolbar.pack(side=TOP, fill=X)

        self.pack(anchor=N, side=TOP, fill=X, expand=False)

    def show_toolbar(event):
        print("Pressed")
        event.cancelButton.pack(side=LEFT, padx=2, pady=2)

def main():
    root = Tk()
    # Width X Height
    root.geometry("500x300+300+300")
    root.update()
    root.minsize(400, 200)
    app = MainWindow(root)
    root.mainloop()

if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:3)

event.cancelButton.pack(side=LEFT, padx=2, pady=2)

这是问题 - 事件不存储小部件

* FIX *

self.cancelButton = ... 然后 self.cancelButton.pack ...