mman1235
mman1235

Reputation: 51

Pillow - FileNotFoundError: No such file or directory: 'Lit_Bulb.jpg'

enter image description here

I just downloaded and extracted Pillow through PyPI, and it seems the modules are now accessible, but when I try to test it adding an image, it shows this error:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Python Projects\Button Puzzle (GUI).py", line 4, in <module>
    image = Image.open("Lit_Bulb.jpg")
  File "C:\Program Files (x86)\PIL\Image.py", line 2288, in open
    fp = builtins.open(fp, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'Lit_Bulb.jpg'

I put the jpg file in the PIL folder, hoping it would find it with the module, but I guess I didn't do it right, can anyone help?

The code I tried:

import tkinter
from PIL import Image, ImageTk

image = Image.open("Lit_Bulb.jpg")
photo = ImageTk.PhotoImage(image)
label = tkinter.Label(main_menu, image = phto)
label.image = photo
label.pack()

main_menu = tkinter.Tk()
main_menu.title("Button Puzzle")
main_menu.configure(background ="SlateGray3")
main_menu.geometry("200x100")

play_button = tkinter.Button(main_menu, text="PLAY")
rules_button = tkinter.Button(main_menu, text= "Rules")
play_button.pack()
rules_button.pack() 

main_menu.mainloop()

Upvotes: 0

Views: 3219

Answers (2)

Digvijayad
Digvijayad

Reputation: 534

  1. It is always good practice to put your images or resources in the same folder as your directory of the main .py file. For example if you have your main files in c:\projects\myProject\ , then you should put the your images in the same folder myProject.

    This way when you open any file or image from within your code, all you need to do is write the name of the file or image. for eg. myImage = Image.open('Lit_Bulb.jpg').

  2. If you don't put your images or files in the same folder than you can access them by specifying the exact directory when you open the file or image. For example, if my image is in a folder in E: drive, then I can access it using this.
    myImage = Image.open('E:\myFolder\Lit_Bulb.jpg').

Note- if you have a big project where you need a lot of files and images, then you should put those images inside a new folder in the same directory as your .py files. After doing this, if you want to open those files, it would look something like this. myImage = Image.open('Images\Lit_Bulb.jpg') since, the Imagesfolder is in the same directory as the py file, you don't need to specify the whole directory. Hope this helps.

Upvotes: 0

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

Pass the full path to the file image = Image.open("path_to_/Lit_Bulb.jpg"), unless the file is in the same directory as your your cwd then python won't be able to find the file.

Upvotes: 2

Related Questions