In Tkinter, we can detect when a window is about to be closed by registering a handler function for the WM_DELETE_WINDOW protocol. This can be triggered by clicking on the X button of the title bar on most desktop environments:
import tkinter as tk
import tkinter.messagebox as mb
class Window(tk.Toplevel):
def __init__(self, parent):
super().__init__(parent)
self.protocol("WM_DELETE_WINDOW", self.confirm_delete)
self.label = tk.Label(self, text="This is another window")
self.button = tk.Button(self, text="Close",
command=self.destroy)
self.label.pack(padx=20, pady=20)
self.button.pack(pady=5, ipadx=2, ipady=2)
def confirm_delete(self):
message = "Are you sure you want to close this window?"
if mb.askyesno(message=message, parent=self):
self.destroy()
Our handler method displays a dialog to confirm window deletion. In more complex programs, this logic is usually extended with additional validations.