Aryaman Pandey
Aryaman Pandey

Reputation: 11

Error in displaying an image using Tkinter

I was trying to run the code:

from tkinter import *

root = Tk()
root.geometry('644x434')
root.minsize(500,200)
root.maxsize(1600,900)
photo = PhotoImage(file='1.jpg')
label1 = Label(image=photo)
label1.pack()

root.mainloop()

but there were lot of errors:

Traceback (most recent call last):
  File "C:/work_in_py/intro-tkinter/tkinter-/tkinter-intro.py", line 6, in <module>
    photo = PhotoImage(file='1.jpg')
  File "C:\python\lib\tkinter\__init__.py", line 4061, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\python\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 "1.jpg"

Process finished with exit code 1

why am I not able to display this image? it's just an image of a car

Upvotes: 0

Views: 1255

Answers (3)

supun lakshan
supun lakshan

Reputation: 1

Your image type seems to be the problem as jpg is not supported. Change the image type to png and it should work.

from tkinter import *
ws = Tk()
ws.title('PythonGuides')
ws.geometry('500x300')
ws.config(bg='yellow')

img = PhotoImage(file="1.png")
label = Label(
    ws,
    image=img
)
label.place(x=0, y=0)

text = Text(
    ws,
    height=10,
    width=53
)
text.place(x=30, y=50)

button = Button(
    ws,
    text='SEND',
    relief=RAISED,
    font=('Arial Bold', 18)
)
button.place(x=190, y=250)

ws.mainloop()

Upvotes: 0

bigbounty
bigbounty

Reputation: 17368

from tkinter import *        
from PIL import ImageTk, Image

app_root = Tk()
img = ImageTk.PhotoImage(Image.open("/Users/bigbounty/Downloads/1.jpg"))
imglabel = Label(app_root, image=img).grid(row=1, column=1)        
app_root.mainloop()

Upvotes: 0

wjakobw
wjakobw

Reputation: 535

tkinter PhotoClass doesn't support jpg: https://docs.python.org/3/library/tkinter.html#images

The docs suggest you to use pillow library if you need other formats. This class should work as a replacement: https://pillow.readthedocs.io/en/4.2.x/reference/ImageTk.html#PIL.ImageTk.PhotoImage

Or just save the image as one of the formats supported directly in tkinter: PGM, PPM, GIF and PNG.

Upvotes: 1

Related Questions