无法从PIL图像构造tkinter.PhotoImage [英] Cannot construct tkinter.PhotoImage from PIL Image
问题描述
当我按下按钮时,我尝试在标签中显示图像,但是图像太大,并且试图调整图像的大小.我创建了此功能:
I try to show a image in a label when I push a button, but the image are too large and I have tried to resize the image. I have created this function:
def image_resize(imageFile):
width = 500
height = 300
image = Image.open(imageFile)
im2 = image.resize((width, height), Image.ANTIALIAS)
return im2
要显示我已创建此功能的图像:
To show the image I have created this function:
def show_image():
label_originalimage ['image'] = image_tk
和带有command=show_image
的按钮:
filename = 'bild_1.jpg'
image_resize = image_resize(filename)
image_tk = PhotoImage(image_resize)
button_open = Button(frame_open, text='Open Image', command=show_image)
我只得到这个:
TypeError : __str__ returned non-string (type instance)
推荐答案
PhotoImage
tkinter
中的class使用文件名作为参数,并且由于无法将image
转换为字符串,因此会抱怨.而是使用PIL.ImageTk
模块中的PhotoImage
类.这对我有用:
The PhotoImage
class from tkinter
takes a filename as an argument, and as it cannot convert the image
into a string, it complains. Instead, use the PhotoImage
class from the PIL.ImageTk
module. This works for me:
from tkinter import *
from PIL import ImageTk, Image
def image_resize(imageFile):
width = 500
height = 300
image = Image.open(imageFile)
im2 = image.resize((width,height), Image.ANTIALIAS)
return im2
def show_image():
label_originalimage ['image'] = image_tk
root = Tk()
filename = './Pictures/Space/AP923487321702.jpg'
image_resize = image_resize(filename)
image_tk = ImageTk.PhotoImage(image_resize)
label_originalimage = Label(root)
label_originalimage.pack()
button_open = Button(root, text='Open Image', command=show_image)
button_open.pack()
root.mainloop()
请注意将image_tk = PhotoImage(image_resize)
更改为image_tk = ImageTk.PhotoImage(image_resize)
.
这篇关于无法从PIL图像构造tkinter.PhotoImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!