Tkinter PhotoImage不存在

时间:2020-01-21 16:25:14

标签: python canvas tkinter pathlib

当我偶然发现一个错误(这是Tkinter的PhotoImage)时,我试图让我的应用程序的运动原型正常工作。

起初,我决定使用Pathlib,但我开始相信这是一个错误(我仍然需要非Windows用户使用此应用程序的方法)。

## -- Setup -- ##
# Imports and Variables
from pathlib import Path # Increases accessibility on mac and Linux machines
from tkinter import *

window = Tk()
window.title("Project 001 - Pre-Alpha 0.1 (pa0.1)")

Game = Canvas(window, width = 1280, height = 720)
Game.config(bg = "white")
Game.pack()

# Defining Images
PlayerImgPath = Path("Assets\\Char\\Player\\Untitled.png") # Player
PlayerImg = PhotoImage(file = PlayerImgPath)

# Sprites
Player = Game.create_image(20, 250, image = PlayerImg) 

运行此命令时出现以下错误

file "D:\PythonD\lib\tkinter\__init__.py", line 3495, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "Assets\Char\Player\Untitled.png": no such file or directory

1 个答案:

答案 0 :(得分:1)

您编写的代码没有问题。 Python无法找到该文件。可能是您运行Python的目录和代码不同的目录。如果您添加Python to system variables,该问题将得到解决。

此外,代替使用双斜杠,按如下所示编写代码将更加实用。

PlayerImgPath = Path(r"Assets/Char/Player/Untitled.png")

还要确保您的python代码在资产目录中。

YourProjectFolder/
├──YourCode.py
└── Assets/
    └── Char/
        └── Player/
            └── Untitled.png