Tkinter Label does not show image

I am trying to learn some tkinter. I can not get tkinter to display the icon. I do not know where this is going. It does not cause any errors and respects the size of the image, but it is invisible. Everything I found on the Internet adds a second link to prevent garbage collection from python, but for some reason this is not a trick. Here is the part of my code that goes wrong:

from Tkinter import *
from PIL import Image, ImageTk

class GUI:

    def __init__(self, master):

        frame = Frame(master)
        frame.pack()

        #status bar
        self.bar = Frame(root, relief=RIDGE, borderwidth=5)
        self.bar.pack(side=TOP)

        self.iconPath = 'data/icons/size.png'
        self.icon = ImageTk.PhotoImage(Image.open(self.iconPath))
        self.icon_size = Label(self.bar, image = self.icon)
        self.icon_size.pack(side=LEFT)

root = Tk()


app = GUI(root)

root.mainloop()
+3
source share
3 answers

When you add an ImageImage or other Image object to the Tkinter widget, you must save your own reference to the image object. If you do not, the image will not always be displayed.

Solution here

+7

- ( , ) , . :

from Tkinter import *
from PIL import Image, ImageTk

class GUI:

    def __init__(self, master):

        frame = Frame(master)
        frame.pack()

        #status bar
        self.bar = Frame(root, relief=RIDGE, borderwidth=5)
        self.bar.pack(side=TOP)

        self.iconPath = 'data/icons/size.png'
        self.icon = ImageTk.PhotoImage(Image.open(self.iconPath))
        self.icon_size = Label(self.bar)
        self.icon_size.image = self.icon  # <== this is were we anchor the img object
        self.icon_size.configure(image=self.icon)
        self.icon_size.pack(side=LEFT)

root = Tk()


app = GUI(root)

root.mainloop()

!

+2

, . - .

+1