Reputation: 131
I'm trying to exit my program when the user decides to close the Tkinter filedialog menu without selecting a file to open. However, although the program exits I keep getting the following message before it terminates:
The debugged program raised the exception unhandled FileNotFoundError [Errno2] No such file or directory
I thought the code I have below would handle something like that though, but maybe I am wrong? Any help or advice would be appreciated.
if root.fileName is None:
sys.exit(0)
else:
pass
Upvotes: 1
Views: 620
Reputation: 49318
When it doesn't return
a filename (the user canceled the dialog), filedialog
will return
an empty string (''
), not None
. Use this instead:
if not root.fileName:
...
Upvotes: 2
Reputation: 229
I have never used tkinter but it seems that even though no file was selected by the user the file dialog it is still trying to look for a file.
In general when handling exception you would place the relevant code in a try except block.
E.G. you may have to import the exception from tkinter for the below to work
try:
# code that can throw an exception
if root.fileName is None:
sys.exit(0)
else:
pass
except FileNotFoundError:
# add code on how you want the error handled
pass
for more details on exception handling have a look at the doc's here
Upvotes: -1