0

Language: Python

Hello There!

This is my code

from tkinter import *

window = Tk()

# you cant set iamages to tkinter directly
# so, you need to create a label

photo = PhotoImage(file="duck.jpg")
label = Label(window, image=photo)
label.pack()

window.mainloop()

The error I get -

Traceback (most recent call last):
  File "d:/development/Python/TheNewBoston/Python/GUI/1/script6.py", line 8, in <module>
    photo = PhotoImage(file="duck.jpg")
  File "C:\Users\hirusha\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 4061, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\Users\hirusha\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 4006, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "duck.jpg"

Link to the image i downloaded - https://image.shutterstock.com/image-photo/mallard-duck-clipping-path-colourful-260nw-1384212383.jpg

what I wan't to do? -

I just simply want to display that image of the duck in my program! like this - This is what i want to do

I am new to python! i know how to read some simple errors.. but i don't understand what they say here..

Any help is appreciated, Thank You!

Hirusha Adikari
  • 150
  • 1
  • 14
  • 1
    I would suggest you try with a .png image. TKinter has had issues with .jpg in the past – Javier Urrestarazu May 02 '21 at 11:30
  • The file you downloaded is not a JPEG image but a [WebP](https://en.wikipedia.org/wiki/WebP). This format is not recognised by Tk (or has the wrong extension). – Laurent LAPORTE May 02 '21 at 11:38
  • https://zeacer.is-a-virg.in/DU3gIT i converted it to a jpg like this – Hirusha Adikari May 02 '21 at 11:42
  • I can confirm that once converted to PNG format, the application works. With the JPEG format, it doesn't work. – Laurent LAPORTE May 02 '21 at 11:43
  • @HirushaAdikari Next time I recommend using [`PIL`](https://pypi.org/project/Pillow/) to open the image and then use [this](https://stackoverflow.com/a/28140228/11106801) to show the image. `PIL` supports a lot of file formats and supports many image manipulations. – TheLizzard May 02 '21 at 11:49

1 Answers1

0

tkinter.PhotoImage don't support ".jpg"

ref

so we can do this by using "Pillow" modual first: install pillow by pip install pillow in windows

then you can try:

from tkinter import *
from PIL import ImageTk, Image
root = Tk()

canv = Canvas(root, width=800, height=800)
canv.grid(row=2, column=3)

img = ImageTk.PhotoImage(Image.open("duck.jpg"))  # PIL solution
canv.create_image(20, 20, anchor=NW, image=img)

mainloop()

it work for me!

Dev Sapariya
  • 151
  • 2
  • 9