Reputation: 11
I'm simply trying to reference an inherited Tkinter screen in a subclass, but for some reason I receive this error:
AttributeError: 'SignUpScreen' object has no attribute '_SignUpScreen__window'
After I try to execute:
self.__signupScreen = SignUpScreen()
And the class code is:
from tkinter import *
class Screen:
def __init__(self, screenTitle, size):
self.__window = Tk()
self.__window.title(screenTitle)
self.__SIZE = size #W x H
def close(self):
#Save all data, then
self.__window.destroy()
class SignUpScreen(Screen):
def __init__(self):
super().__init__("Sign Up", "700x400")
self.__titlelbl = Label(self.__window, text="Sign Up Window", font=("Arial Bold", 22))
def run(self):
self.__titlelbl.grid(column=0, row=0)
self.__window.mainloop()
The IDE claims the error occurs at the following line:
self.__titlelbl = Label(self.__window, text="Sign Up Window", font=("Arial Bold", 22))
I do not understand what the issue is. Can anyone spot the issue?
Upvotes: 1
Views: 46
Reputation: 5051
That's because of Python's name mangling:
Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.
You have two options:
Either change self.__window
to a name without double underscore at the beginning
Use it as self._Screen__window
(not recommended).
Upvotes: 2