简体   繁体   English

TKINTER:关闭所有打开的子 Windows 但离开父 Window 打开

[英]TKINTER: Close All Open Child Windows But Leave Parent Window Open

First, hello and thanks for assisting me with my Python/tkinter question!首先,您好,感谢您协助我解决我的 Python/tkinter 问题!

I would like to be able to close all open child windows and leave the root window open when closing them.我希望能够关闭所有打开的子 windows 并在关闭它们时让根 window 打开。

My sample code is below.我的示例代码如下。 After one opens windows 1 & 2, I would like the third button to close windows 1 & 2 only.在打开 windows 1 & 2 后,我希望第三个按钮仅关闭 windows 1 & 2。

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()

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM