Home > database >  How to access function from another script without causing Attribute error
How to access function from another script without causing Attribute error

Time:10-14

I have 2 scripts: mainmenu.py and join.py; the former gathers an input string from the user and have it displayed in a Label in the latter when button is pressed.

Mainmenu.py:

try:

    if __name__ == "__main__":
    
        .......

        def joinlobby(): #function to open join.py when button is pressed

            if (e2.index("end") == 0): #check if entry is blank

                tk.messagebox.showwarning("Fill the info!")

            else:
           
                master.withdraw()
                subprocess.call([sys.executable, "join.py"])

        def getvalueoflist():

            return e2.get()
    
        e2 = tk.Entry(frame3)
        e2.insert(0, "Enter your name")
        e2.grid(row = 0, column = 0)

        b4 = tk.Button(frame3, text = "Join", 
         bg = "Black", fg = "White", command = lambda: joinlobby())
        b4.grid(row = 1, column = 0)

Join.py

import mainmenu

class GUI:

  def __init__(self):

        .......

        self.lname = tk.Label(self.lnameframe, text = mainmenu.getvalueoflist(), 
        font = ("Times New Roman", 15), fg = "Black")
        self.lname.pack(fill = "both")

Error:

File "join.py", line 32 in __init__
self.lname = tk.Label(self.lnameframe, text = mainmenu.getvalueoflist(), 
        font = ("Times New Roman", 15), fg = "Black")
    self.lname.pack(fill = "both")
AttributeError: module 'mainmenu' has no attribute 'getvalueoflist'

Any help is appreciated.

CodePudding user response:

The code of mainmenu.py has this:

if __name__ == "__main__":
    ...

It's also all inside a try .. block, which seems like not a great idea, but that doesn't affect the problem you're asking about.

The code after the if __name__ == "__main__": will only get executed if __name__ equals '__main__', which is to say, when the mainmenu.py file is executed independently.

So, the functions you define in that block, only get defined if mainmenu.py is executed directly as the main module.

But when you import mainmenu, that doesn't happen. It's loaded as a module, not as the main module, and so the function does not get defined and you get that error.

  • Related