I am currently working on a password manager, where the initial window will ask for login or to create a password. after clicking on login button I wanted to close that initial window and open the main password manager window. Here's my code:-
# ---------------------------- Creating password/ Login ------------------------------- #
def login():
password = my_entry.get()
if saved_pass == password:
# what to write here
pass
else:
# when you type wrong password.
error_label.config(text="Password didn't Match. Try Again.", fg='red')
# error_label.place(x=160, y=330)
def create():
password = my_entry.get()
if len(password) > 8 and ' ' not in password:
error_label.config(text="Your Current Password is Saved.", fg='green')
with open('login_password.json', 'w') as add_pass:
json.dump(password, add_pass)
else:
my_entry.delete(0, END)
error_label.config(text="Password is Too Short or Not Valid.", fg='red')
# ----------------------------Initial UI SETUP ------------------------------- #
initial_window = Tk()
initial_window.title('new page')
initial_window.geometry("460x430")
initial_window.config(padx=20, pady=20, bg=INITIAL_BG)
img = PhotoImage(file='new.png')
canvas = Canvas(width=360, height=250, highlightthickness=0, bg=INITIAL_BG)
canvas.create_image(210, 135, image=img)
canvas.grid(row=1, column=0, columnspan=2, sticky='ew')
my_label = Label(text='Create Password:', bg=INITIAL_BG)
my_label.grid(row=2, column=0, sticky='ew')
my_entry = Entry()
my_entry.grid(row=2, column=1, sticky='ew')
my_entry.focus()
error_label = Label(text=" * Password should have at least 8 characters", fg='black', bg=INITIAL_BG)
error_label.place(x=160, y=330)
save_button = Button(text='Save', width=20)
save_button.place(x=185, y=290)
try:
with open('login_password.json') as data:
saved_pass = json.load(data)
save_button.config(text='Login')
my_label.config(text='Enter Password')
save_button.config(command=login)
error_label.config(text='')
except (json.decoder.JSONDecodeError, FileNotFoundError):
SAVED = False
save_button.config(command=create)
# ----------------------------After UI SETUP ------------------------------- #
window = Tk()
window.title('Password Manager')
window.config(padx=50, pady=50, bg=AFTER_BG)
window.mainloop()
Instead of deleting the original window, just re-use it.
Create a function or class to create the login window, and another one to create the main program. Call the function to create the login window. When the user logs in, destroy all of the widgets for the login window and create the widgets for the main program.
This is easiest if the login window widgets all exist inside a frame. You can then destroy the frame, and all of the other widgets will automatically get destroyed. Or, you can simply loop over all of the children in the main window to destroy them:
for child in window.winfo_children():
child.destroy()
Once you do that, the window is now empty and you can recreate it with all of the main application widgets.