I’m trying create a gui using Tkinter that grabs a username and password and connects to a remote server and does a function. I slapped together some messy code and it more or less worked, but when I tried to recreate it in a tidy module, it broke. Its probably a newbie python error, but I can’t spot it. EDIT: to clarify, when it worked, the only class was setupGui and any methods were under that class. Now that I’ve separated the gui from the methods, its not working.
class setupGui(object):
def __init__(self, parent):
##omited general frame stuff
self.userIn = ttk.Entry(self.topFrame, width = 20)
self.userIn.grid(row = 1, column = 1)
self.passIn = ttk.Entry(self.topFrame, width = 20, show ="*")
self.passIn.grid(row = 2, column = 1)
#Buttons
self.setupbtn = ttk.Button(self.topFrame, text = "Start Setup", command = setup().startSetup())
self.setupbtn.grid(row = 3, column = 0, pady = 10)
class setup(object):
def__init__(self):
self.userName = setupGui.userIn.get()
self.userPass = setupGui.passIn.get()
def startSetup(self):
self.another_related_fucntion # about 4 related functions actually
if __name__ == '__main__':
root = Tk()
gui = setupGui(root)
root.mainloop()
And if I don’t have the command attached to the button, everything works fine (but obviously does diddly squat except look pretty). And when I attached the command, I get this error:
Traceback (most recent call last):
File "macSetup.py", line 211, in <module>
gui = setupGui(root)
File "macSetup.py", line 45, in __init__
self.setupbtn = ttk.Button(self.topFrame, text = "Start Setup", command = setup().startSetup())
File "macSetup.py", line 69, in __init__
self.userName = setupGui.userIn.get()
AttributeError: type object 'setupGui' has no attribute 'userIn'
In your code,
userInis set up as an instance variable ofsetupGuiobjects, not as an attribute of thesetupGuiclass itself.The simplest solution would be to merge the
setupGuiandsetupclasses to movestartSetupin as a method ofsetupGui, then usecommand=self.startSetupwhen you initializesetupbtn—this callsstartSetupas a bound method, andselfshould thus refer to thesetupGuiobject, which you can then use e.g.self.userIn.get()andself.passIn.get()on.If you’d rather keep the logic you have in the
setupclass out of thesetupGuiclass, you can separate it out like this:then add this method to the
setupGuiclass:and instantiate the
Buttonwithcommand=self.dosetup. (I would personally make thesetupclass a standalone function, but I don’t know how complicated yourstartSetuproutine actually is, so I assume you have a good reason for making it a class.)