import tkinter as tk
def check_window():
if window and tk.Toplevel.winfo_exists(window):
label["text"] = window.state()
else:
label["text"] = "Window does not exist"
def close_window():
window.withdraw()
check_window()
def open_window():
global window
if window and tk.Toplevel.winfo_exists(window):
window.deiconify()
else:
window = tk.Toplevel(root)
tk.Label(window, text='This is the child window').pack(padx=50, pady=50)
check_window()
window = None
root = tk.Tk()
label = tk.Label(root, width=30)
label.pack(padx=20, pady=10)
tk.Button(root, text="Update", command=check_window).pack(padx=10, pady=10)
tk.Button(root, text="Deiconify", command=open_window).pack(padx=10, pady=10)
tk.Button(root, text="Withdraw", command=close_window).pack(padx=10, pady=10)
check_window()
root.mainloop()
You might want to withdraw top level windows instead of destroying them when the window is closed by the window manager. To do this you need to specify a protocol.
import tkinter as tk
def check_window():
label["text"] = window.state()
def close_window():
window.withdraw()
check_window()
def open_window():
window.deiconify()
check_window()
window = None
root = tk.Tk()
window = tk.Toplevel(root)
window.withdraw()
tk.Label(window, text='This is the child window').pack(padx=50, pady=50)
window.protocol("WM_DELETE_WINDOW", window.withdraw) # Withdraw instead of delete
label = tk.Label(root, width=30)
label.pack(padx=20, pady=10)
tk.Button(root, text="Update", command=check_window).pack(padx=10, pady=10)
tk.Button(root, text="Deiconify", command=open_window).pack(padx=10, pady=10)
tk.Button(root, text="Withdraw", command=close_window).pack(padx=10, pady=10)
check_window()
root.mainloop()