level42
level42

Reputation: 987

AttributeError: '' object has no attribute '' - Trying to hide/show elements in tkinter

I've been struggling with this for 3 days now, but I cannot seem to get a grasp of this. Quite simply, I'm trying to show (pack) the cancel button when the save button is pressed, but it simply doesn't work.

When I press the save button I get:

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

I'm not sure why this is, I can clearly see the cancelButton object is there. I've read about how the objects might not be initialized or called before I click the button, but again, not sure how this can be, because I see the objects on screen, and I can click the first button.

For the record, I'm trying to follow this tutorial that was posted here: In Tkinter is there any way to make a widget not visible? , but as I try to incorporate this example into my code, which has drastically different code structure, I'm left wit the error above.

My code is below, if anyone could help to explain what is going on.

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

Upvotes: 0

Views: 1280

Answers (1)

Joshua Nixon
Joshua Nixon

Reputation: 1427

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

This is the problem - events doesn't store the widget

* FIX *

self.cancelButton = ... and then self.cancelButton.pack ...

Upvotes: 3

Related Questions