枕头:找不到文件

tit*_*157 2 python tkinter python-3.x tkinter-canvas

我想在 tkinter 的画布上使用图像,但我无法用 Pillow 打开图像。事实上,我的所有图像都与我的代码位于同一个文件夹中,但是当我放置“icon.png”时它不起作用。然后,当我将完整路径放入图像 (C:/Users/myName/Desktop/PythonWork/game/src/icon.png) 时,它就可以工作了。

File "F:\Python\lib\site-packages\PIL\Image.py", line 2312, in open fp = builtins.open(filename, "rb") FileNotFoundError: [Errno 2] No such file or directory: 'icon.png'

因此我的问题是:如何使相对路径起作用?

在此先感谢您的帮助 :)

Amr*_* A. 6

如果要引用与 Image.py 相同目录中的文件,请将其放在 Image.py 中:

import os

# get the directory path of the current python file
my_path = os.path.dirname(__file__)
Run Code Online (Sandbox Code Playgroud)

然后,您可以将要访问的文件的名称附加到该路径。