How to Handle Window Close Events in Tkinter?

Linda Hamilton
Release: 2024-10-27 12:11:30
Original
543 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!