简体   繁体   English

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

[英]image not recognised error whilst trying to add a PNG image to a tkinter window

I'm trying to add images to a tkinter window, and I keep getting the error: 我正在尝试将图像添加到tkinter窗口,并且不断出现错误:

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

I have tried many different ways of adding images to tkinter windows, mostly as question answers from this site and they all give the same error, the code I'm currently using is the simplest version I could find and is as follows: 我尝试了多种向tkinter窗口添加图像的方法,主要是从本网站提问,它们都给出相同的错误,我当前使用的代码是我能找到的最简单的版本,如下所示:

from tkinter import *

root = Tk()

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

root.mainloop()

Im using a mac and running the code in IDLE using python3, after trying for a few hours I've run out of ideas for how this can be fixed so sorry if it's obvious. 我使用mac并使用python3在IDLE中运行代码,尝试了几个小时后,我对如何解决此问题已无所适从,所以很抱歉。

Your tkinter version must not support .png file type for images. 您的tkinter版本不得支持图片的.png文件类型。 Try your program with another file type which your tkinter supports. 尝试使用您的tkinter支持的其他文件类型的程序。

Ok, I've figured it out, I needed to use PIL to open the image and then assign it to a canvas, then pack the canvas to the root, the code I've ended up with is this: 好的,我已经弄清楚了,我需要使用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()

This code achieves the needed effect of displaying a photo in a Tkinter window and also resizing that image. 此代码实现了在Tkinter窗口中显示照片并调整图像大小所需的效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM