Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

python - tkinter PhotoImage doesn't exist?

from tkinter import *

root = Tk()

photo = PhotoImage(file='blueface.png')
label = Label(root, image=photo)
label.pack()

root.mainloop()

The image face.png is in the same directory as this .py script, but when I run it, I get the following error:

 line 5, in <module>
    photo = PhotoImage(file='blueface.png')
 line 3539, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
 line 3495, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "face.png": no such file or directory
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It doesn't matter very much that the image is in the same folder as the script, when you call the file like that without a path python assumes it's in the same folder that you were working on when you started the script. For example, if both the script and the image are in temp folder, and you started your script like this:

python temp/script.py

The interpreter doesn't realize that blueface.png is also in temp and looks for it in the folder that you were in, in this case the parent of temp

What you should do, is either use absolute paths, or use the __file__ to get the full script address first. For example:

photo = PhotoImage(file='/absolute/path/to/image/blueface.png')

Or using the current script's location to build the image's path:

import os
base_folder = os.path.dirname(__file__)
image_path = os.path.join(base_folder, 'blueface.png')
photo = PhotoImage(file=image_path)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...