'TKINTER: Close All Open Child Windows But Leave Parent Window Open
First, hello and thanks for assisting me with my Python/tkinter question!
I would like to be able to close all open child windows and leave the root window open when closing them.
My sample code is below. After one opens windows 1 & 2, I would like the third button to close windows 1 & 2 only.
I appreciate any insights!
import tkinter as tk
root = tk.Tk()
def open():
top = tk.Toplevel(root)
top.title('WINDOW 1')
top.geometry("300x200+550+150")
top.mainloop()
def open2():
top2 = tk.Toplevel(root)
top2.title('WINDOW 2')
top2.geometry("300x200+550+400")
top2.mainloop()
#def close():
#
root.geometry('300x200')
btn_1 = tk.Button(root, text = "Open Window 1", background="#949BA4", command = open)
btn_1.place(x=21, y=20)
btn_2 = tk.Button(root, text = "Open Window 2", background="#949BA4", command = open2)
btn_2.place(x=184, y=20)
btn_3 = tk.Button(root, text = "Close Win 1 & 2", background="#9ABDE9", )
btn_3.place(x=75, y=100)
root.mainloop()
Solution 1:[1]
I found my answer:
import tkinter as tk
root = tk.Tk()
def open():
top = tk.Toplevel(root)
top.title('WINDOW 1')
top.geometry("300x200+550+150")
top.mainloop()
def open2():
top2 = tk.Toplevel(root)
top2.title('WINDOW 2')
top2.geometry("300x200+550+400")
top2.mainloop()
def close():
for widget in root.winfo_children():
if isinstance(widget, tk.Toplevel):
widget.destroy()
root.geometry('300x200')
btn_1 = tk.Button(root, text = "Open Window 1", background="#949BA4", command = open)
btn_1.place(x=21, y=20)
btn_2 = tk.Button(root, text = "Open Window 2", background="#949BA4", command = open2)
btn_2.place(x=184, y=20)
btn_3 = tk.Button(root, text = "Close Win 1 & 2", background="#9ABDE9", command = close)
btn_3.place(x=75, y=100)
root.mainloop()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nebraskan |
