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

daiyue
  • 7,196
  • 25
  • 82
  • 149
  • 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. – Martin Tournoij Mar 22 '16 at 10:41

1 Answers1

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.

Community
  • 1
  • 1
Rob Murray
  • 1,773
  • 6
  • 20
  • 32
  • 1
    it is actually the indentation I put in the code was wrong, `main` and `if` statement should not be indented – daiyue Mar 22 '16 at 11:33