Categories
Python Answers

How to handle the window close event in Tkinter with Python?

Spread the love

Sometimes, we want to handle the window close event in Tkinter with Python.

In this article, we’ll look at how to handle the window close event in Tkinter with Python.

How to handle the window close event in Tkinter with Python?

To handle the window close event in Tkinter with Python, we call the root.protocol method with the 'WM_DELETE_WINDOW' event.

For instance, we write

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()

to call root.protocole with "WM_DELETE_WINDOW" to add a close window handler.

And we specify that we use the on_closing function as the close window handler.

Therefore, when we close the window, we see a message box with title ‘Quit’ and text ‘Do you want to quit’.

And then if we confirm, then root.destroy is called to close the window.

Conclusion

To handle the window close event in Tkinter with Python, we call the root.protocol method with the 'WM_DELETE_WINDOW' event.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *