尝试将PNG图像添加到tkinter窗口时,图像未识别错误

时间:2018-07-10 16:27:13

标签: python tkinter

我正在尝试将图像添加到tkinter窗口中,但不断出现错误:

_tkinter.TclError: couldn't recognize data in image file 'Sun.png'

我尝试了许多不同的方法将图像添加到tkinter窗口中,主要是作为本网站的问题答案,并且它们都给出了相同的错误,我当前使用的代码是我能找到的最简单的版本,如下所示:

from tkinter import *

root = Tk()

photo = PhotoImage(file='Sun.png')
label = Label(root, image=photo)
label.pack()

root.mainloop()

我正在使用Mac并使用python3在IDLE中运行代码,在尝试了几个小时后,我对如何解决此问题的想法不多了,如果很明显,就对不起。

2 个答案:

答案 0 :(得分:0)

您的tkinter版本不得支持图像的.png文件类型。尝试使用您的tkinter支持的其他文件类型的程序。

答案 1 :(得分:0)

好吧,我已经弄清楚了,我需要使用PIL打开图像,然后将其分配给画布,然后将画布打包到根目录,我最终得到的代码是:

from tkinter import *
import PIL
from PIL import ImageTk, Image

root=Tk()
root.geometry('480x360')

cond = 'Sun'

image = Image.open(str(cond) + '.png')
canvas=Canvas(root, height=200, width=200)
basewidth = 150
wpercent = (basewidth / float(image.size[0]))
hsize = int((float(image.size[1]) * float(wpercent)))
image = image.resize((basewidth, hsize), PIL.Image.ANTIALIAS)
photo = ImageTk.PhotoImage(image)
item4 = canvas.create_image(80, 80, image=photo)
canvas.pack(side = TOP, expand=True, fill=BOTH)

root.mainloop()

此代码可达到在Tkinter窗口中显示照片并调整图像大小所需的效果。