-1

I'm new to tkinter and can't seem to wrap my head around oop and I think that's where the problem lies.

This is my code:

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

The error I get from console is:

AttributeError: App instance has no attribute 'button'

I don't get it, wasn't button made when initializing the instance (in init)?

Every other answer I found for similar questions had to do with indentation, but I made sure to double check everything (all tabs and all where I think they should be).

1 Answers1

0

You need to pass the callable to the button instance, not the result.

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

Otherwise you are calling it immediately, so it is executed before the button has actually been defined.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • I think I understand. Basically it runs self.combat() before creating self.button and assigning the button to self.button? Strange though, since I thought that until I clicked the button command wouldn't run... – user1534513 Sep 08 '16 at 15:10
  • It doesn't if you pass the callable as I show above. But otherwise it's just standard Python evaluation rules; everything on the right-hand side must be evaluated before the left hand can be executed. – Daniel Roseman Sep 08 '16 at 15:14
  • Oh... I didn't see the lack of parentheses after self.combat and so I thought you'd rewritten the part of code that was wrong. Thanks. – user1534513 Sep 08 '16 at 15:19