How to Use tkinter’s Protocol Handler in Python


In this example, we will create a window and when a user clicks the close button, the application displays a dialog asking if you really want to end the application.
tkinter provides a mechanism for intercepting system information. Users can intercept the system information and set it up as their own processing routine. This mechanism is called a protocol handler.

The usual protocols are as follows:

  • WM_DELETE_WINDOW: It occurs when the system wants to close the window.
  • WM_TAKE_FOCUS: It occurs when the application gets focus.
  • WM_SAVE_YOURSELF: It occurs when the application needs to store content.

Although this mechanism is established by the X system, the Tk library can handle this mechanism on all operating systems.

The following example intercepts system information WM_DELETE_WINDOW. When the user closes the open window using the [Close] button in the upper right corner of the window, the application displays a dialog asking if you really want to end the application.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# protocolHandler.py

from tkinter import *
import tkinter.messagebox

# handle WM_DELETE_WINDOW event
def handleProtocol():
    # open a dialog
    if tkinter.messagebox.askokcancel("Notice", "Are you sure to close the window"):
       # close the application
       win.destroy()

# create the main window
win = Tk()

# create a protocal
win.protocol("WM_DELETE_WINDOW", handleProtocol)
win.mainloop()

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments