emailman
Posts: 12
Joined: Wed Sep 20, 2017 1:58 pm

Can you customize "exit" action using guizero?

Sat Mar 14, 2020 7:52 pm

I would like to run some code when a guizero App window is closed. I found the code below for tkinter, but I'm not sure if it can be applied to a guizero app or if guizero supports another way of doing the same thing:

Code: Select all

root.protocol('WM_DELETE_WINDOW', doSomething)  # root is your root window

def doSomething():
    # check if saving
    # if not:
    root.destroy()
 

Garvan
Posts: 41
Joined: Sun Jan 05, 2020 9:59 am

Re: Can you customize "exit" action using guizero?

Sun Mar 15, 2020 11:04 am

You can put your cleanup code after app.display() and it will run when app.display() closes.

Code: Select all

from guizero import App, Text

app = App()
text = Text(app, text="hello world")
app.display()
print ("Cleanup")

emailman
Posts: 12
Joined: Wed Sep 20, 2017 1:58 pm

Re: Can you customize "exit" action using guizero?

Sun Mar 15, 2020 2:30 pm

Thanks Garvan. That's a brilliantly simple solution.

scotty101
Posts: 3958
Joined: Fri Jun 08, 2012 6:03 pm

Re: Can you customize "exit" action using guizero?

Mon Mar 16, 2020 10:18 am

If you want to register a function at exit of tkinter, you can use the WM_DELETE_WINDOW method.

using the "tk" property allows you to access the underlying tkinter widget of a guizero widget.

I've now been reliably informed that guizero has an event callback for this already, see below

Code: Select all

def goodbye():
    print("Goodbye!")
    app.destroy()

app.when_closed = goodbye
This is better than the method proposed by Garvan since the app will still exist when this function is called. Lets say you want to save the current text in the window, if you do the Garvan method, the app will have already been destroyed and all the information lost by the time the code after the .display() is executed.
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

emailman
Posts: 12
Joined: Wed Sep 20, 2017 1:58 pm

Re: Can you customize "exit" action using guizero?

Mon Mar 16, 2020 1:52 pm

Hi Scotty,

Thanks for pointing out the handy, but undocumented, event handler "app.when_closed". I agree that's the way to go if you need some information from the app before it ceases to exist, not unlike the dead parrot.

Eric

Return to “Python”