In Tkinter, when a user clicks the "X" button on a window, the WM_DELETE_WINDOW protocol is triggered. To handle this event, you can register a protocol handler.
Protocol handlers allow you to define a specific action to be taken when a protocol is triggered. For WM_DELETE_WINDOW, this action typically involves closing the window or prompting the user for confirmation.
To install a protocol handler, use the protocol method on a Tk or Toplevel widget. The syntax is:
<code class="python">widget.protocol("protocol_name", handler)</code>
where:
The following example demonstrates how to handle the window close event in Tkinter:
<code class="python">import tkinter as tk from tkinter import messagebox root = tk.Tk() def on_closing(): if messagebox.askokcancel("Quit", "Do you want to quit?"): root.destroy() root.protocol("WM_DELETE_WINDOW", on_closing) root.mainloop()</code>
In this example:
The above is the detailed content of How to Handle Window Close Events in Tkinter?. For more information, please follow other related articles on the PHP Chinese website!