Reputation: 597
I have this few lines of code here which opens tkinter toplevel window
which can be destroyed by clicking on the destroy all button
. The challenge when i open several windows and i want to destroy all only one gets destroyed. Have tried the quit
funtion but it close all the window including the the root window
. I only want all the toplevel window to be destroyed.
import tkinter as tk
def open_window():
global top1
top1 = tk.Toplevel()
top1.geometry("100x100")
def destroy_all():
top1.destroy()
root = tk.Tk()
root.geometry("500x500")
b1 = tk.Button(root, text="open", command=open_window)
b1.pack(side=tk.TOP)
b2 = tk.Button(root, text="destroy all", command=destroy_all)
b2.pack(side=tk.BOTTOM)
root.mainloop()
Upvotes: 0
Views: 4442
Reputation: 15226
I like to use list when dealing with dynamically generated widgets/containers. Here I would use a list to hold the Toplevel and then destroy each Toplevel in the list.
import tkinter as tk
def open_window():
list_of_tops.append(tk.Toplevel(root))
list_of_tops[-1].geometry("100x100")
def destroy_all():
for top_window in list_of_tops:
top_window.destroy()
root = tk.Tk()
root.geometry("500x500")
list_of_tops = [] # list to store any toplevel window.
tk.Button(root, text="open", command=open_window).pack(side=tk.TOP)
tk.Button(root, text="destroy all", command=destroy_all).pack(side=tk.BOTTOM)
root.mainloop()
Upvotes: 2
Reputation: 3612
You could loop through all of the widgets you created, and destroy those that are Toplevels
def destroy_all():
for widget in root.winfo_children():
if isinstance(widget, tk.Toplevel):
widget.destroy()
Upvotes: 5