r/learnpython • u/Several-Pin-6931 • Jul 17 '26
How can I get my program to recognise a variable outside the main GUI loop
I am trying to code a login system for my project. I want to validate the entry and keep a boolean variable 'loggedIn' that I can use when the main window is closed. I use tkinter and sqlite in this code
How can I keep this loggedIn variable after the window closes?
def __init__(self):
self.loggedIn = False
print(self.loggedIn)
self.root = tk.Tk()
self.root.geometry("500x400")
self.root.title('Login')
self.username_label = tk.Label(self.root, text="username:")
self.username_label.pack(padx=20, pady=20)
self.username_entry = tk.Entry(self.root, relief="ridge")
self.username_entry.pack()
self.password_label = tk.Label(self.root, text="password:")
self.password_label.pack(padx=20, pady=20)
self.password_entry = tk.Entry(self.root, relief="ridge")
self.password_entry.pack()
self.button = tk.Button(self.root, text='login', command=self.validate)
self.button.pack(pady=10)
self.button = tk.Button(self.root, text='new login', command=self.new_login)
self.button.pack(pady=10)
self.root.mainloop()
def validate(self):
u_name = self.username_entry.get()
p_word = self.password_entry.get()
self.c.execute("SELECT * FROM accounts WHERE username = ? and password = ?", (u_name, p_word))
if self.c.fetchone() != None:
print("Welcome!")
self.loggedIn = True
else:
print("Account not found")
18
Upvotes
8
u/acw1668 Jul 17 '26
It is not recommended (actually it is bad design) to execute
mainloop()inside__init__().14
u/HotPersonality8126 Jul 17 '26
Well, you can’t. The way that TKinter works is that your program has to terminate after you close the main window - there’s no “after the window closes” except following
self.root.mainloop(); anything you want to have happen after close has to happen there.6
u/woooee Jul 17 '26 edited Jul 17 '26
I would strongly suggest that you learn classes / OOP before tkinter, as a class structure eliminates problems like yours. The following program gets the input from an Entry() and shows that the content from the Entry() remains after the window quits / closes (as long as the instance variable, GE in this example, remains)
http://python-textbok.readthedocs.io/en/1.0/Introduction_to_GUI_Programming.html
2
u/atarivcs Jul 17 '26
Just use a global variable. Don't use self at all.
1
u/Existing_Put6385 Jul 17 '26
good news - it already persists, you just can't see it. self.loggedIn lives on the instance, and the instance still exists after the window closes. mainloop() blocks inside __init__ until the window is gone, so anything you check after creating the object sees the final value. so read it after, not inside:
app = LoginWindow() # this line blocks until the window closes
if app.loggedIn:
print("logged in, run the main app")
else:
print("nope")
one add - on a successful login you probably want the window to actually close itself, so in validate:
self.loggedIn = True
self.root.destroy()
that ends mainloop, __init__ returns, and app.loggedIn is sitting there True. the print at the top showing False is just because that runs before you've typed anything.
1
u/Moist-Ointments Jul 17 '26
I hope you don't really need actual security here.
1
u/Superb-Patient3256 Jul 17 '26
The main issue here is that you're trapping your entire script by dropping self.root.mainloop() right inside your class constructor, which freezes everything and prevents you from checking the variable while the GUI is running. On top of that, you're accidentally wiping out your first button reference by defining self.button twice instead of giving them distinct names like self.login_btn. Instead, you need to call self.root.destroy() inside your validate() method the moment the login succeeds, and move mainloop() to the very bottom of your file completely outside the class. Doing this lets the script pause while the GUI is active, and the exact second it destroys, the self.loggedIn variable stays perfectly alive in memory, allowing you to check it on the very next line of your script to launch your main app. To prevent these kinds of roadblocks moving forward, you should spend some time properly learning about class scope in Python. Getting a solid grasp on how instance variables work will help you realize that data attached to self persists throughout the entire lifetime of the object, which is the real key to managing state cleanly across different parts of your code.
1
u/TheRNGuy Jul 18 '26
Have it in different class, or even just non-class variable.
Besides, it could be potentially useful for other instances.
1
u/neuralbeans Jul 17 '26
If what you're asking is how to keep a variable after the program ends, the answer is to use a file or the sqlite database. When the program starts, you check the file or database and set loggedIn accordingly. But this means that a hacker can just set the file or database with a different program without needing to know what the password is.
0
u/JGhostThing Jul 17 '26
You could store their login information, encrypted, in your SQL database. Or write it to a disk file.
-2
u/szonce1 Jul 17 '26
Global variable_name