Warm tip: This article is reproduced from serverfault.com, please click

File not found, even though the directory is correct

发布于 2015-05-10 21:27:46

I am currently trying to make a game, and I am importing an image for a button from a the same folder the python file is from. The method:

dirname, filename = os.path.split(os.path.abspath(sys.argv[0]))
imagepath = os.path.join(dirname, "redvase.png")
vase1 = Button(root, relief=FLAT, background="white", image=imagepath)
vase1.place(x=330,y=240,height=30,width=30)

The output (imagepath) comes out as C:\Users\ - - \Desktop\Pythonproject\redvase.png

My file is at that exact path, but I still get an error saying that that file does not exist.

vase1 = Button(root, relief=FLAT, background="white", image=imagepath)
......
_tkinter.TclError: image "C:\Users\- -\Desktop\Pythonproject\redvase.png" doesn't exist

If it helps, I am using Windows and Python 3.4.3.

Questioner
Daniel Li
Viewed
0
Daniel Li 2015-05-12 09:09:37

The image attribute for a button takes an input of an Image object, not a path to an image file. In order to get an image, you can use a PhotoImage:

photo=PhotoImage(file="redvase.gif")
vase1 = Button(root, relief=FLAT, background="white", image=photo)