-1

I simply want to show an image in a label widget. I managed the task by the following code:

import tkinter as tk
from PIL import Image,ImageTk
import requests

root=tk.Tk()
url="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/500px-SNice.svg.png"
imageurl=requests.get(url, stream=True)
image=Image.open(imageurl.raw)
img = ImageTk.PhotoImage(image.resize(size=(500,500)))
origPictureBox = tk.Label(root, image=img, anchor=tk.NW, height=500, width=500)
origPictureBox.config(image=img)
origPictureBox.pack(side=tk.TOP)
root.mainloop()

However, when I put the main tasks into a function, the picture is not displayed:

import tkinter as tk
from PIL import Image,ImageTk
import requests

def initUI(root):
    url="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/500px-SNice.svg.png"
    imageurl=requests.get(url, stream=True)
    image=Image.open(imageurl.raw)
    img = ImageTk.PhotoImage(image.resize(size=(500,500)))
    origPictureBox = tk.Label(root, image=img, anchor=tk.NW, height=500, width=500)
    origPictureBox.config(image=img)
    origPictureBox.pack(side=tk.TOP)

root=tk.Tk()
initUI(root)
root.mainloop()

Can somebody explain this behavior? If other items are to be displayed (buttons, etc.), they are visible, it's just the image that hides.

The same happens if I use a class instead of the function initUI.

It's my first question in stackOverflow and I am sorry, if the answer is obvious.

Ingo
  • 1

1 Answers1

0

You need to keep reference to the image, or its get garbage collected

So add:

l = tk.Label(root)
l.image = img

Full code

import tkinter as tk
from PIL import Image,ImageTk
import requests

def initUI(root):
    url="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/500px-SNice.svg.png"
    imageurl=requests.get(url, stream=True)
    image=Image.open(imageurl.raw)
    img = ImageTk.PhotoImage(image.resize(size=(500,500)))
    l = tk.Label(root)
    l.image = img
    origPictureBox = tk.Label(root, image=img, anchor=tk.NW, height=500, width=500)
    origPictureBox.config(image=img)
    origPictureBox.pack(side=tk.TOP)

root=tk.Tk()
initUI(root)
root.mainloop()
coderoftheday
  • 1,987
  • 4
  • 7
  • 21