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
  • 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. Commented Jun 15, 2018 at 13:00
  • Bryan is correct. Using protocol to redirect the "window close" event to a custom function is the best option. Commented Jun 15, 2018 at 13:07

2 Answers 2

5

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 ..")
Sign up to request clarification or add additional context in comments.

2 Comments

Why is the __enter__(self): required?
@ArchismanPanigrahi The __enter__ method is called when an instance of the class is used in ("entering") a with statement.
-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.

6 Comments

Why do I need to bind this to the button ? I just need to execute the command when the window is closed. Can I bind this to already existing buttons?
You can bind it to any widget. Like I said, if you bind it to the main window, it'll fire the method twice.
FWIW root_win.bind('<Destroy>', good_bye) works for me, the function is called only once. Python 3.6.5 from python.org on windows 7 32 bits.
You don't need to bind to any widgets. just bind to the root window.
I tried that, which resulted in the function being called twice.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.