2

I would like to use images with tkinter's canvas but I can't open image with Pillow. In fact, I have all my images in the same folder as my code but when I put "icon.png" it doesn't work. Then when I put the full path to the image (C:/Users/myName/Desktop/PythonWork/game/src/icon.png) , it works.

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'

Therefore my question is : How do I make the relative path to work ?

Thanks in advance for your help :)

titi157
  • 157
  • 4
  • 12

1 Answers1

6

If you want to reference files in the same directory as in Image.py, put this in Image.py:

import os

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

You can then append to that path the name of the file you want to access.

Shady Mohamed Sherif
  • 15,003
  • 4
  • 45
  • 54
A.A.
  • 402
  • 1
  • 4
  • 19