Home > front end >  How do i close a old window each time a new window is oppened in tkinter
How do i close a old window each time a new window is oppened in tkinter

Time:02-14

I have a simplified code below of 2 separate screens. How do I have it so that when one screen is opened the old one is then closed?

Whilst i don't have multiple screens in this example i would like to be able to to this for 6-9 screens dependent upon GUI design.

any help on the subject would be greatly appreciated.

from tkinter import *
import os
import time
from tkinter import simpledialog

def login():
    global screen2
    screen2 = Toplevel(screen)
    screen2.title("Login")
    screen2.geometry("530x290")
    Label(screen2, text = "please enter details below to login").pack()
    Label(screen2, text = "").pack()
   
    calibration1 = StringVar()
    calibration2 = StringVar()
    calibration3 = StringVar()
   
    global calibration1_entry
    global calibration2_entry
    global calibration3_entry
   
    calibration1_entry= Entry(screen2, textvariable = calibration1).place(x=350, y=70)
    calibration2_entry = Entry(screen2, textvariable = calibration2).place(x=350, y=120)
    calibration3_entry = Entry(screen2, textvariable = calibration3).place(x=350, y=170)

def main_screen():
    global screen
    screen = Tk()
    screen.geometry("530x290")
    screen.title("Remote Monitoring Site 1")
    Label(text = "Remote Monitoring Site 1", bg = "grey", width = "300", height = "2", font = ("Calibri", 13)).pack()
    Label(text = "").pack()
    Button(text = "Login", width = "30", height = "2", command = login).pack()
    Label(text = "").pack()
   
    screen.mainloop()

main_screen()

CodePudding user response:

You can assign screen2 to be None at the beginning and make sure to destroy and reopen it, if it isn't None:

def login():
    global screen2

    if screen2 is None: # if screen2 is not Toplevel
        screen2 = Toplevel(screen)
    else:
        screen2.destroy() # destroy and start new screen
        screen2 = Toplevel(screen)
    ...
    ...

def main_screen():
    global screen2,screen

    screen = Tk()
    screen2 = None # Assign to None at the beginning
    ...
    ...

This will also make sure no two Toplevel is open at the same time.

CodePudding user response:

You can make more then one script for example to code login screen in one script, main menu in other, etc. Then you can use import os to close and open scripts. Function would be something like:

def login():
    if username == "admin" and password == "admin":
        file = 'python3 main_menu.py' # or you can do it
        root.destroy()                # proper way with db
        os.system(file)
  • Related