不必跟踪哪些 Toplevel 处于活动状态,您可以在哨兵上使用弱引用- 只是传递给每个 Toplevel 并保存在引用中的一些对象。当每个 Toplevel 死亡(关闭)时,让它删除其对哨兵的引用。当最后一个对哨兵的引用被删除时,weakref 回调self.no_sentinel
将被自动调用,依次root.destroy
为你调用。
import Tkinter as tk
import weakref
class Sentinel(object):
pass
class Window(tk.Toplevel):
def __init__(self, master, sentinel, **kwargs):
title = kwargs.pop('title')
self.sentinel = sentinel
tk.Toplevel.__init__(self, master, **kwargs)
self.protocol("WM_DELETE_WINDOW", self.ondelete)
self.label = tk.Label(self, text=title)
self.label.pack(padx=10, pady=10)
def ondelete(self):
self.destroy()
del self.sentinel
class App(object):
def __init__(self, master, **kwargs):
self.master = master
sentinel = Sentinel()
parent = Window(master, sentinel, title='Parent')
child = Window(master, sentinel, title='Child')
self._ref = weakref.ref(sentinel, self.no_sentinel)
# When we exit `__init__` only two strong references to sentinal
# remain -- in parent and child. When both strong references are
# deleted, `self.no_sentinel` gets called.
def no_sentinel(self, *args):
self.master.destroy()
root = tk.Tk()
root.withdraw()
app = App(root)
root.mainloop()
或者,您可以使用该multiprocessing
模块生成另一个进程来创建另一个 Tkinter 窗口和主循环,但会比上述解决方案消耗更多内存,并且如果您希望单独的进程共享信息,则需要您设置某种形式的进程间通信.