Skip to content

Instantly share code, notes, and snippets.

@0xpizza
Last active October 31, 2019 15:45
Show Gist options
  • Select an option

  • Save 0xpizza/aa9f81920a5ef4357677fdf2070a246b to your computer and use it in GitHub Desktop.

Select an option

Save 0xpizza/aa9f81920a5ef4357677fdf2070a246b to your computer and use it in GitHub Desktop.
from tkinter import *
from tkinter.ttk import *
class App(Frame):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.count_failed_logins = 0
self.logged_in_user = None
# sits at bottom of login screen; invisible until invalid login
self.error_label = Label(self, foreground='red')
self.show_login_screen()
def clear_widgets(self):
for w in self.winfo_children():
w.pack_forget()
def logout(self, *events):
self.clear_widgets()
self.logged_in_user = None
self.show_login_screen()
def show_main_window(self):
Label(self, text='Welcome, {}'.format(self.logged_in_user)).pack()
Frame(self).pack(fill=Y, expand=True) # vertical padding
l = Label(self, text='logout', font='helvitica 7')
l.pack(anchor='e')
l.bind('<Button-1>', self.logout)
def show_login_screen(self):
Frame(self).pack(fill=Y, expand=True) # vertical padding
f = Frame(self)
f.pack()
Label(f, text='Username:').grid(row=0,column=0, pady=4)
Label(f, text='Password:').grid(row=1,column=0, pady=4)
self.name_input = Entry(f, width=20)
self.pass_input = Entry(f, width=20, show='☺')
self.name_input.grid(row=0,column=1, pady=4)
self.pass_input.grid(row=1,column=1, pady=4)
Button(self, text='login', command=self.verify_creds).pack()
Frame(self).pack(fill=Y, expand=True) # vertical padding
self.error_label.pack()
# set cursor on the username
self.name_input.focus_set()
# allow the user to press Enter instead of clicking login button
self.name_input.bind('<Return>', self.verify_creds)
self.pass_input.bind('<Return>', self.verify_creds)
def verify_creds(self, *events): # events are discarded if it's bound
u = self.name_input.get()
p = self.pass_input.get()
if u == 'admin' and p == 'admin':
# login correct, do whatever
self.clear_widgets()
self.logged_in_user = u
self.error_label.configure(text='')
self.show_main_window()
else:
if self.count_failed_logins == 0:
self.error_label.configure(text='invalid credentials')
self.count_failed_logins += 1
class Root(Tk):
'''
main window object serves as style manager and entry point for
the main app widget
'''
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.title('Login Example')
self.geometry('500x400')
self.style = Style(self) # ttk makes it look nicer
self.style.configure("TEntry", padding=4)
self.style.configure("TLabel", font='courier 10 bold', padding=3)
App(self).pack(expand=True, fill=BOTH)
def main():
Root().mainloop()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment