简体   繁体   English

如何使用类在 tkinter 中显示调整大小的图像?

[英]How do I display resized images in tkinter using classes?

I'm trying to display a resized image, but I'm not sure how to do that using classes.我正在尝试显示调整大小的图像,但我不确定如何使用类来做到这一点。 This code works fine:此代码工作正常:

image = Image.open(Image_Location)
image = image.resize((200, 200), Image.ANTIALIAS)
image = ImageTk.PhotoImage(image)

But I need to do this in a class method (because I need multiple for the main project and it would take too long to do it seperately), how do I do it?但是我需要在 class 方法中执行此操作(因为我需要多个主项目并且单独执行此操作需要很长时间),我该怎么做? This is what I have tried so far:这是我到目前为止所尝试的:

class Planet:
    def __init__(self, name, picture):
        self.name = name
        self.picture = tk.PhotoImage(file=picture)

    @classmethod
    def resize_image(cls, picture):
        image = Image.open(picture)
        image = image.resize((200, 200), Image.ANTIALIAS)
        image = ImageTk.PhotoImage(image)

earth = Planet("earth",Image_Location)
earth_resized = earth.resize_image(Image_Location)

test1 = Label(root, image=earth_resized)
test2 = Label(root, image=earth.picture)
test1.pack()
test2.pack()

And when I pack both labels, I get a white space (I think that is supposed to be the resized image) and the unsized image.当我打包两个标签时,我得到一个空白(我认为这应该是调整大小的图像)和未调整大小的图像。 Thanks!谢谢!

You forgot to return the resized image from the method -- it should look like this:您忘记从该方法返回调整大小的图像 - 它应该如下所示:

    @classmethod
    def resize_image(cls, picture):
        image = Image.open(picture)
        image = image.resize((200, 200), Image.ANTIALIAS)
        return ImageTk.PhotoImage(image)

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

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