[英]How to avoid unhandled exception in Tkinter?
I'm trying to exit my program when the user decides to close the Tkinter filedialog menu without selecting a file to open. 当用户决定关闭Tkinter文件对话框而不选择要打开的文件时,我正在尝试退出程序。 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
When it doesn't return
a filename (the user canceled the dialog), filedialog
will return
an empty string ( ''
), not None
. 当它没有return
的文件名(用户取消了对话框), filedialog
会return
一个空字符串( ''
),而不是None
。 Use this instead: 使用此代替:
if not root.fileName:
...
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. 我从未使用过tkinter,但似乎即使用户未选择文件对话框中的文件,它仍在尝试查找文件。 In general when handling exception you would place the relevant code in a try except block. 通常,在处理异常时,应将相关代码放在tryexcept块中。
EG you may have to import the exception from tkinter for the below to work EG,您可能必须从tkinter导入异常才能使以下代码正常工作
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 有关异常处理的更多详细信息,请在此处查看文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.