Home > Software design >  labelled image object doesn't exist
labelled image object doesn't exist

Time:05-07

I get the pictures from the wikipedia in a class and add them to the dict, when I want to return it and add the result to the label image, I get an error

import tkinter as tk
import urllib.request
from PIL import Image, ImageTk
from io import BytesIO
import time

image_dat = {}
class add:
    def __init__(self, url):
        self.test(url)

    def test(self, url):
        if url not in image_dat.keys():
            u = urllib.request.urlopen(url)
            raw_data = u.read()
            u.close()
            im = Image.open(BytesIO(raw_data))
            im = im.resize((25, 25), Image.ANTIALIAS)
            photo = ImageTk.PhotoImage(im)
            photo.im = photo
            image_dat[url] = photo
            return image_dat[url]

if __name__ == '__main__':

    root = tk.Tk()
    label = tk.Label()
    label.pack()
    img = add("https://upload.wikimedia.org/wikipedia/commons/f/fb/Check-Logo.png")
    label['image'] = img
    tk.mainloop()

Error

CodePudding user response:

This error is because after returning from the test function, the image object is not getting returned by the constructor of the add class.

For example, just to test, if done like this in the test function:

.
.
photo.im = photo
image_dat[url] = photo
#if created a label here with that image, it will work fine:
label = tk.Label(root, image=image_dat[url])
label.pack()

This way you get no error. This shows everything is fine with the code written inside the test function.


So, in order to fix the code given in the question:

Since, the constructor __init__() can only return None, if you want to return some other object when a class is called, then use the __new__() method.

.
.
class add:
    def __new__(cls, url):
        return cls.test(url)
      
    def test(url):
        .
        .

Using these changes your issue gets solved.

  • Related