Search code examples
python-3.xtkintertkinter-entry

How to close a particular window without closing the whole app in Tkinter?


I'm creating a Tic-Tac-Toe program using tkinter, in which I would like to take the name of the user using entry and the next name to be given in a separate window, but before that I would like to automatically close the previous window.

I used a common variable called root (mainloop also) for displaying all the windows. Once I destroy the root, the whole program stops. Should I name a separate variable with tk.Tk() to proceed and use it in other windows? I just can't understand.

Can anyone help me...


Solution

  • Yes, destroying the root will close the entire app.
    If you want to close windows while keeping the app running, you can use a tk.Toplevel to pop a window open, and be able to close it while continuing other operations.

    maybe like this:

    import tkinter as tk
    
    
    def popup():
        p = tk.Toplevel(root)
        p.title('popup')
        tk.Label(p, text='I will self destroy in 3 seconds').pack()
        p.after(3000, p.destroy)
    
    
    root = tk.Tk()
    btn = tk.Button(root, text='pop a new window', command=popup)
    btn.pack()
    
    root.mainloop()