Home >Backend Development >Python Tutorial >How to Handle Window Close Events in Python Tkinter?
Handling Window Close Events in Python Tkinter
How do you manage the scenario where a user closes a window by clicking the designated 'X' button within a Tkinter program?
Answering the Query:
Tkinter introduces the concept of protocol handlers to manage the communication between an application and its corresponding window manager. The WM_DELETE_WINDOW protocol, frequently employed in this context, delineates the course of action when a user opts to close a window manually.
To establish a handler for the WM_DELETE_WINDOW protocol, utilize the protocol method. This protocol installation is applicable to Tk and Toplevel widgets.
Code Illustration:
<code class="python">import tkinter as tk from tkinter import messagebox root = tk.Tk() def on_closing(): user_choice = messagebox.askokcancel("Quit", "Do you want to quit?") if user_choice: root.destroy() root.protocol("WM_DELETE_WINDOW", on_closing) root.mainloop()</code>
In this example, the on_closing function prompts the user for confirmation before proceeding with window destruction.
The above is the detailed content of How to Handle Window Close Events in Python Tkinter?. For more information, please follow other related articles on the PHP Chinese website!