I can only open png images with Tkinter

Asked

Viewed 231 times

0

I’m trying to open up images jpeg with Tkinter using the PhotoImage, but I can’t. The program and image are in the same folder, but still it gives error:

couldn’t open "image.jpeg": no such file or directory

I’m using the following code:

from tkinter import *

janela = Tk()
janela.geometry('1300x740')

imagem = PhotoImage(file="imagem.jpeg")

lb = Label(janela, image = imagem)
lb.place(x = 550, y = 320)`

janela.mainloop()
  • You can show us which files are in your directory the main.py file runs in ?

1 answer

0

Tkinter Photoimage does not work with all image formats:

https://docs.python.org/3.3/library/tkinter.html

Note that the documentation highlights this part in the following excerpt:

Photoimage can be used for GIF and PPM/PGM color bitmaps.


When you try to open an image not supported by Tkinter Photoimage, the generated exception is the following:

couldn’t recognize data in image file "image.jpeg"

Your exception is distinct from this, so you are also having problem in the location of the file, make sure the file extension is actually not jpg, it’s more common to be that way.


To work with a jpg, you can use the PIL (Python Imaging Library):

https://pillow.readthedocs.io/en/stable/

Installing it by Pip as documentation guides:

python -m Pip install Pip

python -m Pip install Pillow


Working with PIL, your example would be as follows:

from tkinter import *
from PIL import Image, ImageTk 

janela = Tk()
janela.geometry('1300x740')

jpg = Image.open("imagem.jpeg")
imagem = ImageTk.PhotoImage(jpg)

# Pode ser tudo em apenas uma linha
# imagem = ImageTk.PhotoImage( Image.open("imagem.jpeg") ) 

lb = Label(janela, image = imagem)
lb.place(x = 550, y = 320)

janela.mainloop()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.