code beginner
code beginner

Reputation: 285

Catching a Tkinter exception for a missing file

I'm writing a Tkinter program that loads some .png images.

Since files can be faulty or non-existent, it is good to use a try-except block. I'm first checking the file with generic Python. Then I load the image file into Tkinter if it passes the generic Python try-except block:

ok = True
try:
    image_file = open("cat.png")
    image_file.close()
except IOError:
    ok = False

if ok:
    self.image = PhotoImage(file="cat.png")

This has to load the image file twice: once for the Python check, and once for Tkinter. Also, there is no guarantee the Tkinter image load attempt will work. If the file were arriving over a network, it is possible the file was available for the Python try-except call, but was then suddenly not available for the Tkinter call.

When I intentionally crash the program by making a call to an unavailable file, I get:

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

This is exactly the error type (file not found) that I am trying to catch inside of Tkinter. I've hunted around, but I have been unable to find out a way for Tkinter to try-except its own call to: PhotoImage(...).

How can I safely load the PNG?

Upvotes: 0

Views: 805

Answers (1)

abarnert
abarnert

Reputation: 366113

You don't need to make tkinter try-except its own call; just try-except your call to tkinter:

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

For example:

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)

Upvotes: 4

Related Questions