Text of discuss.python.org › t › class-composition-between-two-classes › 37531 as Styx crawled it on Nov 20, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

Class Composition Between Two Classes - Python Help - Discussions on Python.org

Class Composition Between Two Classes Python Help onePythonUser (Paul) October 31, 2023, 12:40am 1 Hello, I have created two classes (for now). One class is being used as the main (Testing), and the other is being used as a composition class (Login). When I attempted to run the main class, I had initially attempted to do it via the following lines: if __name__ == "__main__": app = Testing() app.mainloop() Doing it this way, it failed.

After many iterations of different set ups, I finally tried the following way (adding the ‘tk’ in front of the mainloop()) and it appears to work … not sure why: if __name__ == "__main__": app = Testing() tk.mainloop() Not sure why it works this way. Can someone please give a valid explanation. Another issue that I came across is that if I set the variable testing to ‘True’, the code appears to execute as expected.

However, if I set it to ‘False’, then I get the following exception: RuntimeError: Too early to run the main loop: no default root window Here is my test code snippet: import tkinter as tk import datetime # This list contains the authorized users to run tests on this test station. authorizedUserList = {'James': 'CA456', 'Robert': 'CA841', 'Roger': 'CA341'} class Login(tk.Tk): def __init__(self): super().__init__() self.verified = False tk.Tk.title(self,'PN: F4581-01 Test') # Window title (not real pn) tk.Tk.geometry(self, '280x150') login_info = tk.LabelFrame(self, padx = 15, pady = 10, text = "Login Info") tk.Label(login_info, text = "First name").grid(row = 0) tk.Label(login_info, text = "Password").grid(row = 1) self.username = tk.Entry(login_info) self.username.grid(row = 0, column = 1, sticky = tk.W) self.password = tk.Entry(login_info, show = '*') self.password.grid(row = 1, column = 1, sticky = tk.W) self.btn_start_test = tk.Button(self, text = "Start Test", command = self.verifyUser) self.btn_start_test.bind("<Return>", self.verifyUser) # Add 'Enter' key as additional input # to 'Start Test' button login_info.pack(padx = 10, pady = 10) self.btn_start_test.pack(padx = 10, pady = 10, side = tk.BOTTOM) self.username.focus_set() # Put cursor in 'First Name' cell entry def verifyUser(self, *args): name = self.username.get().title() password = self.password.get().upper() if name in authorizedUserList: if authorizedUserList[name] == password: print('\nCredentials verified.') # for testing purposes self.verified = True else: print('Unauthorized user!

Try Again.') self.clear_login() #return self.verified def clear_login(self): self.username.delete(0, tk.END) self.password.delete(0, tk.END) class Testing: def __init__(self): #super().__init__() testing = True # This is the testing loop while testing: self.login = Login() # Instantiate class object 'Login' via composition print(self.login) #self.valid_user = self.login() #verifyUser().verified print('Entered while loop and passed login') #print(self.valid_user) ## if(self.login.verifyUser() == True): ## ## print('Test start time:', datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) ## print('\nBeging testing ...') ## ## else: ## print('Wrong credentials!

Please try again.') testing = False # Force a stop to the while loop if __name__ == "__main__": app = Testing() tk.mainloop() Any help / clarification would be appreciated. By the way, to test the code snippet in the affirmative, you may type the following: First name: james Password: ca456 … this is from a combination as defined in the dictionary at the top. csm10495 (Charles Machalow) October 31, 2023, 5:14am 2 tk.mainloop() takes the registered tk.Tk ‘windows’ and starts running them.

The alternative for a single ‘window’ would be to run window.mainloop() . In your case, you have Testing but you can’t access your Login object to call mainloop() on it. If we simplify the Testing object we can access the tk.Tk and call mainloop() : ... class Testing: def __init__(self): self.login = Login() if __name__ == "__main__": app = Testing() app.login.mainloop() This functionally works out the same way as your existing version.

For the testing = False issue, you’re hitting that since in your original code, if testing is False a tk.Tk object isn’t created. You need at least one in order to call tk.mainloop() . onePythonUser (Paul) October 31, 2023, 3:09pm 3 Hello, thank you for your response. 1st issue : I tried your suggestion, and it does work. My interpretation from your response is that because we are using the tk module via inheritance in the Login class, we have to incorporate it somehow into the mainloop().

In my original method, I used ‘tk’ explicitly and your method we use it implicitly since the Login class has tk.Tk as a master. However, I also noticed that the Login class had its first letter lower case. When I tried it as app.Login.mainloop() , it failed (with ‘L’ as upper case - take away is that the composition class has to be entered all lower case). My conjecture (correct me if I’m wrong), is that if you’re going to use a class as a composition, and that class has a module class as a master, you have to somehow include the inherited master class into the main loop call?

In your method, we do so implicitly by including that class (the Login class). Please advise. 2nd issue : Ok, here it appears that I have to incorporate some class, be it a dummy class which does nothing potentially, has to be included so that it at least makes a reference to the ‘tk.Tk’ class. Is this correct? Now, in a practical application, there would be many more classes that may or may not have tk.Tk class. Would these need to be included as part of the mainloop() as well somehow or only one would suffice?

Again, thank you for your insight and helping this novice understand python a little better. csm10495 (Charles Machalow) October 31, 2023, 11:20pm 4 For 1: tkinter.mainloop() is a method that can will run the ‘main loop’ for tkinter. It runs window.mainloop() for the main (i think first) ‘window’. You have one window so tkinter.mainloop() does the same thing as running .mainloop() on your instance of Login . You controlled the casing of the Login variable.

For example: login = Login() # now i have a Login instance named 'login' LOGIN = Login() # now i have another Login instance named LOGIN # I can now do login.<thing> and LOGIN.<thing>, etc. # I don't recommend having both, but I'm just showing for demonstration purposes. I’m not 100% what you mean by ‘master’ in your descriptions. You simply have a class Testing with a login property on it. In Login ’s case: class Login(tk.Tk): ... denotes that Login inherits from tk.Tk .

Therefore Login is a child class of tk.Tk . tk.Tk is also a parent class of Login . For 2: You have Login which inherits from tk.Tk . So you can do whatever you need in Login . Each window of the application would likely be its own child of tk.Tk . onePythonUser (Paul) November 1, 2023, 2:45am 5 Hello, thank you for the additional clarification. Issue 1 I referenced the tk.Tk class as the ‘master’ class because the code snippet is based on this module.

Additionally, in my test snippet: Login - Base class (inheriting from the tk.Tk classes —> Login(tk.Tk): ) Testing - Derived class (although ‘Derived’ / ‘Base’ nomenclature is more appropriately used for inheritance, I am using this naming convention loosely because the Testing class is using the Login class via composition) Regarding the lower case login, ok, I understand now. This is because I instantiated the Login class as: self.login = Login() … here ‘login’ is lower case.

For mainloop call, we do not use the ‘else’. This slipped by but now I got it. Issue 2: Ok, understood. Issue 3 (New one): Stay tuned … I am working on expanding this code snippet. So might have additional questions. For now, all cleared up. Thank you very much. Much appreciated. ************************************** UPDATE *************************************** I have a question for the def ini

The rest of this page is on the live site.