python - 枕头 : File not found

标签 python python-3.x tkinter tkinter-canvas

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

文件“F:\Python\lib\site-packages\PIL\Image.py”,第 2312 行,打开 fp = builtins.open(文件名, "rb") FileNotFoundError: [Errno 2] 没有这样的文件或目录:'icon.png'

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

在此先感谢您的帮助:)

最佳答案

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

import os

# get the directory path of the current python file
my_path = os.path.dirname(__file__)

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

关于python - 枕头 : File not found,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43396378/

相关文章:

python - _tkinter.TclError : couldn't open "sample.gif": no such file or directory

python - 在 for 循环中为 tkinter Entry 小部件设置值时出现问题

python - 将行星经度转换为 360 度格式的 python 代码

python - dict_key 对象不支持索引-python 3

Python/wxPython : Importing CSV file onto wxGrid not displaying to fit on frame

python - 使用不同的参数同时运行相同的函数

python - 如何使用 numpy where 查找多条记录

python - 在不知道编码的情况下使用 Python 读取文件

python-3.x - 有没有一种简单的方法可以循环迭代枚举?

python - 在单独的标签文本中使用时,变量具有不同的值