如何避免 Tkinter 中未处理的异常?
How to avoid unhandled exception in Tkinter?
当用户决定关闭 Tkinter 文件对话框菜单而不选择要打开的文件时,我试图退出我的程序。但是,尽管程序退出,但我在终止前不断收到以下消息:
The debugged program raised the exception unhandled FileNotFoundError [Errno2] No such file or directory
我认为下面的代码可以处理类似的事情,但也许我错了?如有任何帮助或建议,我们将不胜感激。
if root.fileName is None:
sys.exit(0)
else:
pass
如果它不是 return
文件名(用户取消了对话框),filedialog
将 return
一个空字符串 (''
),而不是 None
。改用这个:
if not root.fileName:
...
我从未使用过 tkinter,但似乎即使用户未选择文件,文件对话框仍会尝试查找文件。
通常在处理异常时,您会将相关代码放在 try except 块中。
例如。您可能必须从 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
有关异常处理的更多详细信息,请查看文档的 here
当用户决定关闭 Tkinter 文件对话框菜单而不选择要打开的文件时,我试图退出我的程序。但是,尽管程序退出,但我在终止前不断收到以下消息:
The debugged program raised the exception unhandled FileNotFoundError [Errno2] No such file or directory
我认为下面的代码可以处理类似的事情,但也许我错了?如有任何帮助或建议,我们将不胜感激。
if root.fileName is None:
sys.exit(0)
else:
pass
如果它不是 return
文件名(用户取消了对话框),filedialog
将 return
一个空字符串 (''
),而不是 None
。改用这个:
if not root.fileName:
...
我从未使用过 tkinter,但似乎即使用户未选择文件,文件对话框仍会尝试查找文件。
通常在处理异常时,您会将相关代码放在 try except 块中。
例如。您可能必须从 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
有关异常处理的更多详细信息,请查看文档的 here