Tkinter 错误:无法识别图像文件中的数据 [英] Tkinter error: Couldn't recognize data in image file

查看:49
本文介绍了Tkinter 错误:无法识别图像文件中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 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.)

更多选项:

  • 这个答案 提到,tkinter 仅适用于 gif 图像.尝试使用 .gif 图像.
  • 如果这不起作用,请使用 PIL,如此答案中所述.莉>
  • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆