[Tkinter-discuss] Exception protection to tk calls

Michael Lange klappnase at web.de
Wed Mar 31 04:10:42 EDT 2021


Hi,

On Wed, 31 Mar 2021 06:53:26 +0000
Vasilis Vlachoudis <Vasilis.Vlachoudis at cern.ch> wrote:

> Is there any recommendation which tkinter calls have to be protected
> with an exception handling I occasionally receive traceback errors from
> my users on various calls like: grab_current, grab_release, focus_get
> most of the times I protect them with with a TclError handler catching
> exceptions like_tkinter.TclError: bad window path name
>
> Also which type of exception has to be protected, this is the first
> time I've got a KeyError from a tkinter call, which normally should be
> innocent focus_get()"

it is a bit hard to guess what's going on without a real code example.
It seems like you get these errors when either calling for example
grab_release() on a widget that has already been destroyed or, in the
last example, calling focus_get() while a messagebox is being displayed
(not sure how this can actually happen in real-world code, I was only
able to reproduce that error message with a non-sensical example, like

>>> def foo():
...     root.after(1000, lambda: print(root.focus_get()))
...     messagebox.showinfo()
...
) .

I know that this is not really an answer to your question, but my guess
is that all of these situations may actually be caused by programming
errors which, once they have been discovered, should rather be fixed
properly than worked around with a try-except clause.

For example, if the window on which grab_release() is called might no
longer exist, something like

if widget.winfo_exists():
    widget.grab_release()

might do the trick.

If you want to use try-except protection anyway, I don't think that there
is any general rule which methods should be protected with which
exception type. I think the only way to find out is to examine the
tkinter code and find out for yourself which exception(s) are likely to
occur. For example with focus_get() I think the KeyError caused by
nametowidget() is probably the only exception one might expect.
Of course one could always play it safe with something like:

try:
    focus = self.focus_get()
except:
    focus = None

Best regards

Michael


.-.. .. ...- .   .-.. --- -. --.   .- -. -..   .--. .-. --- ... .--. . .-.

Death, when unnecessary, is a tragic thing.
		-- Flint, "Requiem for Methuselah", stardate 5843.7


More information about the Tkinter-discuss mailing list