首页 > 解决方案 > Tkinter PhotoImage 不存在

问题描述

当我偶然发现一个错误时,我试图让我的应用程序的运动原型正常工作,这是 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

标签: pythoncanvastkinterpathlib

解决方案


你写的代码没有问题。Python 找不到该文件。可能是你运行Python的目录和代码不同的目录。如果将Python 添加到系统变量中,问题将得到解决。

此外,不要使用双斜杠,而是将代码编写如下更实用。

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

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

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

推荐阅读