Check when tkinter window closes

Question:

from tkinter import *

root = Tk()
root.geometry("400x400")
if not 'normal' == root.state():
    print('just closed')

root.mainloop()

I wanted to check if this tkinter window closes, print('just closed') gets executed. I have also tried doing this with a while loop but that does not work since it does not reach the root.mainloop().

Asked By: Giannis Tsakas

||

Answers:

Only place the print statement after the mainloop()

from tkinter import *

root = Tk()
root.geometry("400x400")

root.mainloop()
print('just closed')
Answered By: thomkell

There is another way to detect when the window is closed, which is to bind a function to the <Destroy> event. However, for the Tk widget (unlike for Frame or Button for instance), .bind() also binds to all the widget’s children, therefore simply using

root.bind("<Destroy>", lambda event: print('just closed'))

will not produce the desired result. Indeed, ‘just closed’ will be printed for the destruction of each widget in the window. To avoid this, we can check that the widget triggering the event is indeed the main window:

def on_destroy(event):
    if event.widget != root:
        return
    print("just closed")

Here is an example:

import tkinter as tk

root = tk.Tk()
tk.Label(root, text="Some text").pack(padx=10, pady=10)
tk.Button(root, text="Quit", command=root.destroy).pack(padx=10, pady=10)

def on_destroy(event):
    if event.widget != root:
        return
    print("just closed")

root.bind("<Destroy>", on_destroy)
root.mainloop()
Answered By: j_4321
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.