捕获丢失文件的 Tkinter 异常



我正在编写一个加载一些.png图像的Tkinter程序。

由于文件可能有错误或不存在,因此最好使用 try-except 块。 我首先使用通用Python检查文件。 然后,如果图像文件传递了通用的 Python try-except 块,我将图像文件加载到 Tkinter 中:

ok = True
try:
image_file = open("cat.png")
image_file.close()
except IOError:
ok = False
if ok:
self.image = PhotoImage(file="cat.png")

这必须加载图像文件两次:一次用于 Python 检查,一次用于 Tkinter。 此外,不能保证 Tkinter 图像加载尝试会起作用。 如果文件是通过网络到达的,则该文件可能可用于 Python try-except 调用,但随后突然不可用于 Tkinter 调用。

当我通过调用不可用的文件故意使程序崩溃时,我得到:

tkinter.TclError: couldn't open "fakefile.png": no such file or directory

这正是我试图在 Tkinter 中捕获的错误类型(找不到文件(。 我四处寻找,但一直找不到让特金特尝试的方法——除了它自己的呼唤:PhotoImage(...)

如何安全地加载 PNG?

你不需要让 tkinter try——除了它自己的调用;只是尝试——除了你对 tkinter 的调用:

try:
self.image = PhotoImage(file="cat.png")
except tkinter.TclError:
# do whatever you wanted to do instead

例如:

try:
self.image = PhotoImage(file="cat.png")
except tkinter.TclError:
self.cat = Label(text="Sorry I have no cat pictures")
else:
self.cat = Label(image=self.image)

最新更新