无法从PIL图像构造tkinter.PhotoImage [英] Cannot construct tkinter.PhotoImage from PIL Image

查看:261
本文介绍了无法从PIL图像构造tkinter.PhotoImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我按下按钮时,我尝试在标签中显示图像,但是图像太大,并且试图调整图像的大小.我创建了此功能:

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屋!

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