Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

python - Tkinter Label does not show Image

I'm trying to learn some tkinter. I can't get tkinter to display an icon. I don't know where it goes wrong. It does not produce any error and it respects the size of the image, but it's invisible. Everything I found online tells to add a second reference to prevent garbage collection from python, but somehow this did not the 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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you add a PhotoImage or other Image object to a Tkinter widget, you must keep your own reference to the image object. If you don’t, the image won’t always show up.

Decision here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...