0

I tried to call a method from within a class like this,

from tkinter import * 

class LoginFrame(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)   

        self.parent = parent        
        self.initUI()

    # initialize the login screen UI  
    def initUI(self):
        self.parent.title("Login Screen")


    def make_label(parent, caption=NONE, side=TOP, **options):
        label = Label(parent, text=caption, **options)

        if side is not TOP:
            label.pack(side=side)
        else:
            label.pack()

        return label


    def main():
        top = Tk()

        # create a background image 
        photo_bg = PhotoImage(file="building.gif")          
        building = make_label(top, image=photo_bg)

        top.mainloop()


    if __name__ == '__main__':
        main()

I got an errorNameError: name 'make_label' is not defined, how to resolve this. Also I tried to make the code as importable as possible, to run as a module, what's the best way to do that?

many thanks

1
  • 3
    I think something went wrong with the indentation when you pasted your code, please edit the code to fix that. Is make_label supposed to be a function or a class method? I suspect the latter? If so, then you need to use ClassInstance.make_label() or self.make_label() (from inside the class instance). You're never actually making a LoginFrame class instance anywhere btw. Commented Mar 22, 2016 at 10:41

1 Answer 1

1

You are trying to reference the method of a class, so you need to reference the class and then reference the method within the scope of that class like so:

building = LoginFrame.make_label(top, image=photo_bg)

As for import-ability, using classes and functions like you have looks fine to me. If you import this then the code within the if __name__ == '__main__': statement won't be run when it is imported as it is not the initial python script to be run (see here) but the functions and classes of this script can still be referenced.

Sign up to request clarification or add additional context in comments.

1 Comment

it is actually the indentation I put in the code was wrong, main and if statement should not be indented

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.