python - 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
解决方案
你写的代码没有问题。Python 找不到该文件。可能是你运行Python的目录和代码不同的目录。如果将Python 添加到系统变量中,问题将得到解决。
此外,不要使用双斜杠,而是将代码编写如下更实用。
PlayerImgPath = Path(r"Assets/Char/Player/Untitled.png")
还要确保您的 python 代码位于资产目录中。
YourProjectFolder/
├──YourCode.py
└── Assets/
└── Char/
└── Player/
└── Untitled.png
推荐阅读
- android - 如何从片段 Android 工作室中的文本视图访问数据
- c++ - 如何从不均匀分布的文件中添加字符?
- jquery - 变量中对象的 JQuery 取消绑定事件
- c# - 如何使用 C# 和 HttpRequestMessage 在 Trello 中设置自定义字段?
- python - TypeError:使用 tf.map_fn() 时,“张量”对象不能解释为整数
- nginx - 是否可以将本地文件缓存到 Nginx
- html - 更改屏幕/窗口高度时如何使弹出模式内部元素div调整大小?
- mongodb - 在猫鼬中更改数组的顺序不会保存
- python - pandas_datareader,ImportError:无法导入名称“urlencode”
- windows - 如何从 Win32 API 中的总线关系获取设备实例路径