简体   繁体   中英

showing an image in tkinter window error - couldn't recognize data error

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!

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM