0

My program has to do some task after the tkinter window is closed.

When the 'X' button is pressed, it should print "The window is closed, how to do it"???

my code is

from tkinter import *
root = Tk()
Label(root, text = "This is for stackoverflow('X' button clicked code)").pack()
root.mainloop()

Actually I am looking for something like return value...

Prakhar Parikh
  • 177
  • 2
  • 13

2 Answers2

2

You can use WM_DELETE_WINDOW protocol to detect if root window is closed.

root.protocol("WM_DELETE_WINDOW", lambda: print ("The window is closed."))

Also, mainloop() is a sort of while loop which keeps the GUI running.

You can also add print('The window is closed.') after it

root.mainloop()
print('The window is closed.')
  • in my program, the roots name is login_root, but it doesnot print the statement it gives the following error – Prakhar Parikh Jul 24 '21 at 06:44
  • Traceback (most recent call last): File "C:\Users\admin\PycharmProjects\firstfrog\CodingBee\complete_app.py", line 2505, in login_root.protocol("WM_DELETE_WINDOW", lambda: print("The window is closed.")) File "C:\python 32 bit\lib\tkinter\__init__.py", line 2189, in wm_protocol return self.tk.call( _tkinter.TclError: can't invoke "wm" command: application has been destroyed – Prakhar Parikh Jul 24 '21 at 06:44
0

Try printing the statement after the mainloop() ends. Look at @BryanOakley's comment -

root.mainloop()
print("The window is closed")

The print statement would not run until you close the window or when the mainloop ends

Edit - Maybe something like this will work -

import tkinter as tk

root = tk.Tk()

l = tk.Label(root,text='hiiii')
l.pack()

root.mainloop()

print('The application is closed, new window opening')


win = tk.Tk()

l = tk.Label(win,text='byeee')
l.pack()

win.mainloop()
PCM
  • 2,881
  • 2
  • 8
  • 30