Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

python - Tkinter error: Couldn't recognize data in image file

I'm trying to put a jpg image to a tkinter canvas. tkinter gives me this error:

couldn't recognize data in image file

I use the code from the documentation:

canv = Canvas(root, width=80, height=80, bg='white')
canv.grid(row=2, column=3)

img = PhotoImage(file="bll.jpg")
canv.create_image(20,20, anchor=NW, image=img)

Same thing with png images. Even tried to put an image into a label widget, but got the same error. What's wrong?

I am using Python 3 on Mac. Python file and image are in the same folder.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your code seems right, this is running for me on Windows 7 (Python 3.6):

from tkinter import *
root = Tk()

canv = Canvas(root, width=80, height=80, bg='white')
canv.grid(row=2, column=3)

img = PhotoImage(file="bll.jpg")
canv.create_image(20,20, anchor=NW, image=img)

mainloop()

resulting in this tkinter GUI:

GUI with this image as bll.jpg: image

(imgur converted it to bll.png but this is working for me as well.)


More options:

  • This answer mentions, tkinter is working only with gif images. Try using a .gif image.
  • If this is not working, use PIL as stated in this answer.

Update: Solution with PIL:

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

canv = Canvas(root, width=80, height=80, bg='white')
canv.grid(row=2, column=3)

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

mainloop()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...