Tkinter错误:无法识别图像文件中的数据 [英] Tkinter error: Couldn't recognize data in image file
问题描述
我正在尝试将jpg图像放到tkinter画布上. tkinter给我这个错误:
I'm trying to put a jpg image to a tkinter canvas. tkinter gives me this error:
无法识别图像文件中的数据
couldn't recognize data in image file
我使用文档中的代码:
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)
与png图像相同.甚至试图将图像放入标签小部件中,但出现了相同的错误.怎么了?
Same thing with png images. Even tried to put an image into a label widget, but got the same error. What's wrong?
我在Mac上使用的是Python 3. Python文件和图像位于同一文件夹中.
I am using Python 3 on Mac. Python file and image are in the same folder.
推荐答案
您的代码似乎正确,这在Windows 7(Python 3.6)上为我运行:
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()
产生此tkinter GUI:
resulting in this tkinter GUI:
,其图像为bll.jpg
:
(imgur将其转换为bll.png
,但这也对我有用.)
(imgur converted it to bll.png
but this is working for me as well.)
更多选项:
- 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.
更新:使用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()
这篇关于Tkinter错误:无法识别图像文件中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!