Search code examples
pythonpython-3.xtkintertkinter-entry

How to open a new window in Tkinter if my login username and password are correct in my login window?


I want to open a new window once my username and password are correct in my first login window, my login window file is named main.py and i have defined a function to validate my username and password

for i in c:
    if user == i['USUARIO'] and contra == i['CONTRASEÑA']:
        messagebox.showinfo(title='Correcto', message='Usuario y Contraseña Correctos')
        menuPrincipal.destroy()
        mainformuser.open()
        break
else:
    messagebox.showerror(tittle=None, message='Usuario o Contraseña Incorrectos')

it works fine until menuPrincipal.destroy() which is my first window, i used destroy() to close it once the username and password are correct, the problem is when I want to open a new window, my second window file is named mainformuser.py and in that file I've defined a function def open(): and imported to the first file. it works(though give me this error

invalid command name "2716849470592time" , while executing "2716849470592time" ("after" script))

but I think I should use def open(): in my new window because I need to do many things in my second window and all that should be included in def open():, What's the right way to insert my windows once i push the login button and my username and password are right??, any idea please let me know, thanks

UPDATE

This is my second window file mainfomuser.py

from tkinter import *
from time import *
from PIL import ImageTk, Image
import sqlite3
from tkinter import messagebox

 
def open():

    top = Tk()
    top.title('Menú Principal')
    top.configure(background='black')
    top.resizable(True, True)
           
    app_width = 1300
    app_height = 777
    screen_width = top.winfo_screenwidth()
    scree_height = top.winfo_screenheight()
    x = (screen_width/2) - (app_width/2)
    y = (scree_height/2.2) - (app_height/2)
    top.geometry(f'{app_width}x{app_height}+{int(x)}+{int(y)}')


Solution

  • It is always nice to keep your code clean by keeping everything inside a separate module and importing it. But there is a thing, or two, to note with tkinter.

    • Whenever you say Tk() you are creating an instance of a Tcl interpreter. So now throughout the code, this interpreter will be used, unless mentioned to use a new one. So if you import the new file, make sure to say destroy the old Tk() before making one more Tk().

    • But here I think its better here to use Toplevel() for your new window instead of Tk() and instead of menuPrincipal.destroy() say menuPrincipal().withdraw() to hide the main window and later menuPrincipal.deiconify() to bring it back up whenever you please to do so.

    I don't know much about your code, so if you don't intend to reuse the window you are destroying, then you can proceed with destroying it instead of hiding it.