我目前正在尝试制作游戏,并且正在从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。
按钮的图像属性采用图像对象的输入,而不是图像文件的路径。为了获得图像,你可以使用PhotoImage:
photo=PhotoImage(file="redvase.gif")
vase1 = Button(root, relief=FLAT, background="white", image=photo)