Home  >  Article  >  Backend Development  >  How to Handle Window Close Events in Tkinter?

How to Handle Window Close Events in Tkinter?

Linda Hamilton
Linda HamiltonOriginal
2024-10-27 12:11:30544browse

How to Handle Window Close Events in Tkinter?

Handling Window Close Events in Tkinter

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

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.

Installing a Protocol Handler

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:

  • protocol_name is the name of the protocol (e.g., "WM_DELETE_WINDOW")
  • handler is the function to be called when the protocol is triggered

Example Usage

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 on_closing function is defined to prompt the user for confirmation before closing the window.
  • The protocol method is used to register on_closing as the handler for the WM_DELETE_WINDOW protocol.
  • The mainloop method runs the main event loop, waiting for events like window close requests.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn