Jonathan
Jonathan

Reputation: 201

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

I'm new to python and have been messing around with Tkinter and now Pillow.

I'm trying to make an image an attribute of a class, and then have that image open as an image in a Tkinter Label. Here's some sample code. My Tkinter windows are working right aside from when I try to do this exact thing, so if there are any errors in the Tkinter code below it's purely as a result of writing samples.

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

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

This opens the image in a new window

foo.image.show()

But this throws an error when I try to run it.

def testwindow:
    root = Tk()

    <necessary code>

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

    mainloop()

The error that I get is:

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

I've successfully achieved the result I want NOT using this method (using PhotoImage(file=xxxx) to open whatever I want within my Tkinter definition) but ideally the image is an attribute of the object so I can use it elsewhere.

Any thoughts of the right way to do this?

Thanks!

Upvotes: 0

Views: 4233

Answers (1)

Miraj50
Miraj50

Reputation: 4407

You can "create" the PhotoImage of the file and then store it in self.image and then use that whenever needed. Here is an example.

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()

Upvotes: 1

Related Questions