Windows系统可以使用:
root.protocol("WM_DELETE_WINDOW", your_function_here)
我不知道其他操作系统,因为我没有测试它在Windows以外的任何东西。
在课堂上也能很好地工作。
self.root.protocol("WM_DELETE_WINDOW", self.your_method_here)
我加入一些代码到您的文章来说明其使用。请注意,当您按下X按钮时,程序将符合close_program方法。
编辑:无法在Mac上测试我已经添加了我认为可以解决您的问题。我已经在close_program方法中添加了一条if语句,以在尝试关闭之前检查顶层是否存在。
更新:我添加了一个检查变量win
来处理可能的错误,如果顶层从未打开,但仍然尝试关闭根窗口。
from tkinter import *
class Window(Toplevel):
def __init__(self, master):
Toplevel.__init__(self)
self.protocol("WM_DELETE_WINDOW", self.close_program)
def close_program(self):
print ("destroying Window")
self.destroy()
class MainWindow(Tk):
def __init__(self):
Tk.__init__(self)
Button(self, command=self.open_window).grid(row=0, column=0)
self.protocol("WM_DELETE_WINDOW", self.close_program)
def open_window(self):
global win
win = Window(self)
win.grab_set()
def close_program(self):
if 'win' in globals():
if win.winfo_exists() == 1:
print("top level still active")
else:
print("destroying MainWindow")
self.destroy()
else:
print("destroying MainWindow")
self.destroy()
app = MainWindow()
app.mainloop()
我已经更新了我的回答让我知道,如果它是你在找什么。 –
你真正的问题是什么?你想改变/完成什么? –
@ TadhgMcDonald-Jensen我想阻止用户在关闭子窗口之前关闭父窗口。 – Shibli