2

I am using tkinter with python.

Is it possible to execute a certain command (eg. print ("hello")) before closing the window, when close button is pressed?

I am using the close button of the desktop environment (along with maximize and minimize) and not any special close button.

Note that I am asking how to execute a certain command before closing, and not how to close the window (which can already be done with the window buttons). So this is not a duplicate of this question

  • 2
    You say it's not a duplicate, but it is. Even though the wording is different ("handle" vs "run a command"), the answer is the same, and it's to use the `protocol` method. – Bryan Oakley Jun 15 '18 at 13:00
  • Bryan is correct. Using protocol to redirect the "window close" event to a custom function is the best option. – Mike - SMT Jun 15 '18 at 13:07

2 Answers2

4

Depending on what you want to do when the window closes, a possible solution is to wrap your GUI into a class, initialize it in a with statement and do your work in the __exit__() method:

import tkinter


class MainWindow(object):

  def __init__(self):
    print("initiated ..")
    self.root = tkinter.Tk()

  def __enter__(self):
    print("entered ..")
    return self

  def __exit__(self, exc_type, exc_val, exc_tb):
    print("Main Window is closing, call any function you'd like here!")



with MainWindow() as w:
  w.root.mainloop()

print("end of script ..")
Wololo
  • 1,249
  • 1
  • 13
  • 25
-1

Here's what I came up with:

import tkinter as tki

def good_bye(*args):
    print('Yo, dawg!')

root_win = tki.Tk()
my_button = tki.Button(root_win, text='I do nothing')
my_button.pack(padx=20, pady=20)
my_button.bind('<Destroy>', good_bye)
root_win.mainloop()

The event is triggered when the widget is destroyed, which happens when you close the main window. Strangely, if you bind the event to the main window, it is triggered twice. Maybe somebody more knowlegeable can shed some light on that.

uwain12345
  • 356
  • 2
  • 21