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

python-找不到文件,即使目录正确

(python - File not found, even though the directory is correct)

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

我目前正在尝试制作游戏,并且正在从python文件所在的同一文件夹中为按钮导入图像。方法:

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)

输出(图像路径)显示为 C:\Users\ - - \Desktop\Pythonproject\redvase.png

我的文件位于该确切路径,但是仍然出现错误,指出该文件不存在。

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

如果有帮助,我正在使用Windows和Python 3.4.3。

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

按钮的图像属性采用图像对象的输入,而不是图像文件的路径。为了获得图像,你可以使用PhotoImage:

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