繁体   English   中英

将图像用作类对象属性,然后在Tkinter标签小部件中打开该图像

[英]Using an image as an class object attribute, then opening that image in a Tkinter label widget

我是python的新手,一直在与Tkinter和现在的Pillow混在一起。

我试图使图像成为类的属性,然后将该图像作为Tkinter标签中的图像打开。 这是一些示例代码。 我的Tkinter窗口除了我尝试执行此操作外,还可以正常工作,因此,如果下面的Tkinter代码中有任何错误,则完全是由于编写示例造成的。

class PicTest:
    def __init__(self, name, image):
        self.name = name
        self.image = image

foo = PicTest('foo', Image.open('foo.png'))

这会在新窗口中打开图像

foo.image.show()

但这在我尝试运行它时引发错误。

def testwindow:
    root = Tk()

    <necessary code>

    foo_testlabel = Label(root, image=foo.image, height=xxx, width=xxx)
    foo_testlabel.pack()

    mainloop()

我得到的错误是:

_tkinter.TclError: image "<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=119x96 at 0x10D9FE240>" doesn't exist

我已经成功实现了我不希望使用此方法的结果(使用PhotoImage(file = xxxx)在Tkinter定义中打开所需的任何对象),但理想情况下,图像是对象的属性,因此我可以在其他地方使用它。

对正确的方法有什么想法?

谢谢!

您可以“创建”文件的PhotoImage ,然后将其存储在self.image ,然后在需要时使用它。 这是一个例子。

import tkinter as tk

class PicTest:
    def __init__(self, name, image):
        self.name = name
        self.image = tk.PhotoImage(file=image)

root = tk.Tk()
foo = PicTest('foo', '/path/to/image/file')

def testwindow():
    foo_testlabel = tk.Label(root, image=foo.image)
    foo_testlabel.pack()

testwindow()
root.mainloop()

暂无
暂无

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

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