[Newbie] Tkinter Question
ckaynor at zindagigames.com
Tue Feb 23 17:41:07 EST 2016
On Tue, Feb 23, 2016 at 2:19 PM, Wildman via Python-list <
python-list at python.org> wrote:
> I am familiar with OO programming but I am new to Python
> and Tkinter. I am working on a gui program that creates
> a couple of temporary files. As part of the Exit button
> command they are deleted. If the program is shut down
> using the window close button [X], the exit button code
> is not executed and the temporary files are left behind.
> That is a serious no-no.
> Is there a way to capture close button click to prevent
> the program from closing and instead execute a command?
> I'm talking about something like the Form_QueryUnload
> event in Visual Basic.
> Alternately is there a way to just disable the button
> or prevent it from being displayed in the first place?
> Any help appreciated.
There are a few options involved, however one other case to consider is if
the user force kills the app (or the whole system is shut down improperly,
such as a power loss). In those cases, should the temp files be removed? If
yes, you'll need to use OS features to ensure the files are properly
deleted by letting the OS know they are temporary.
If the temp files need to be removed no matter what, the primary option is
using the delete=True arguments. Alternatively, you can probably use
os.open with O_TEMPORARY (I belive this is the same
as FILE_FLAG_DELETE_ON_CLOSE in the Win32 API, and there is probably
something similar for Linux).
If you only care if the user closes the app properly (no ending the process
on Windows), you can perform the clean-up when the mainloop returns, aka
Tkinter.Tk().mainloop(). Based off other GUI systems, this will only occur
once all windows have been closed. Another option would be to use Python's
atexit library: https://docs.python.org/3/library/atexit.html. atexit has
the advantage that you could register/unregister the handlers when needed,
rather than maintaining your own list to clean-up. Tkinter may also have
some hook you can use to get when it is exiting, but I do not know what
that is. The same limitations regarding OS exits will apply, however.
If you need somewhere in the middle, you can try signal handlers, which,
for some types of external exits, will fire, but it is not certain.
More information about the Python-list