Home >Backend Development >Python Tutorial >How to Handle the Window Close Event in Tkinter?
Managing user interactions is crucial in GUI programming. One essential event to handle is the window close event, which occurs when the user clicks the "X" button in the window's title bar. In Tkinter, this event can be handled using protocol handlers.
Tkinter's WM_DELETE_WINDOW protocol represents the user explicitly closing the window through the window manager. By installing a handler for this protocol, you can define the desired behavior when this event occurs.
To install a handler for the WM_DELETE_WINDOW protocol, use the protocol method on a Tk or Toplevel widget. The syntax is as follows:
<code class="python">widget.protocol("WM_DELETE_WINDOW", callback)</code>
Where widget is the Tk or Toplevel widget whose close event you want to handle, and callback is the function to execute when the window is closed.
The following code demonstrates how to handle the window close event in a Tkinter program:
<code class="python">import tkinter as tk from tkinter import messagebox # Create a Tk root window root = tk.Tk() # Define the callback function for the close event def on_closing(): # Prompt the user for confirmation before quitting if messagebox.askokcancel("Quit", "Do you want to quit?"): root.destroy() # Install the handler for the window close event root.protocol("WM_DELETE_WINDOW", on_closing) # Start the Tkinter event loop root.mainloop()</code>
In this example, when the user clicks the "X" button, a confirmation dialog appears prompting them to confirm quitting. If the user confirms, the destroy method is called to close the window. Otherwise, the event is ignored.
The above is the detailed content of How to Handle the Window Close Event in Tkinter?. For more information, please follow other related articles on the PHP Chinese website!