Handling window deletion
Under some circumstances, you might want to perform an action before the user closes a top-level window, for instance, to prevent you losing unsaved work. Tkinter allows you to intercept this type of event to conditionally destroy the window.
Getting ready
We will reuse the App
class from the preceding recipe, and we will modify the Window
class so that it shows a dialog to confirm closing the window:

How to do it...
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", ...