0

I'm trying to make an online image viewer in which you can open online images (from a link) in Tkinter. This is my code:

from tkinter import *
from PIL import ImageTk, Image
import requests
from io import BytesIO

root = Tk()

var = StringVar()
entry = Entry(root, textvariable=var)
entry.pack()


def add_image():
imagelab.config(image=WebImage(entry.get()).get())


Button(root, text='Go! ', command=add_image).pack()


class WebImage:
def __init__(self, url):
u = requests.get(url)
self.image = ImageTk.PhotoImage(Image.open(BytesIO(u.content)))

def get(self):
return self.image


imagelab = Label(root)
imagelab.pack()

root.mainloop()

In this, its all working, and no errors are coming. But, the image is not displayed. I think it is loaded, but not displayed.

Thanks!

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Your `WebImage` object gets deleted at the end of `add_image` which deletes the `ImageTk`. Create and store all of your `WebImage` objects in a list – TheLizzard May 17 '21 at 14:15
  • 2
    Does this answer your question? [Why does Tkinter image not show up if created in a function?](https://stackoverflow.com/questions/16424091/why-does-tkinter-image-not-show-up-if-created-in-a-function) – acw1668 May 17 '21 at 14:16
  • No... I have seen this, but i don't know how to use it. Can you please share some code? Sorry, I am a beginner with Tkinter –  May 17 '21 at 14:17

1 Answers1

0

Try this:

from tkinter import *
from PIL import ImageTk, Image
import requests
from io import BytesIO

root = Tk()

var = StringVar()
entry = Entry(root, textvariable=var)
entry.pack()

webimages_list = []

def add_image():
    image = WebImage(entry.get())
    webimages_list.append(image)
    imagelab.config(image=image.get())


Button(root, text="Go!", command=add_image).pack()


class WebImage:
    def __init__(self, url):
        u = requests.get(url)
        self.image = ImageTk.PhotoImage(Image.open(BytesIO(u.content)))

    def get(self):
        return self.image


imagelab = Label(root)
imagelab.pack()

root.mainloop()

It stores all of the WebImage objects in a list called webimages_list. That stops python from garbage collecting the WebImage objects.

TheLizzard
  • 7,248
  • 2
  • 11
  • 31