Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - How to add an Image to a widget? Why is the image not displayed?

How can I add an image to a widget in tkinter?

Why when I use this code it does not work:

some_widget.config(image=PhotoImage(file="test.png"), compound=RIGHT)

but this does work?:

an_image=PhotoImage(file="test.png")
some_widget.config(image=anImage, compound=RIGHT)
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Your image is getting garbage collected when you try to use it in the first version.

effbot is ancient, but here's good snippet:

You must keep a reference to the image object in your Python program, either by storing it in a global variable, or by attaching it to another object.

In the second version the image is declared at the global level.

Here's another example that would demonstrate this issue, that you would expect to also work, after all it's the same code just in a function

Doesn't work:

import tkinter as tk
from PIL import ImageTk

root = tk.Tk()
def make_button():
    b = tk.Button(root)
    image = ImageTk.PhotoImage(file="1.png")
    b.config(image=image)
    b.pack()
make_button()
root.mainloop()

Does work:

import tkiner as tk
from PIL import ImageTk

root = tk.Tk()
def make_button():
    b = tk.Button(root)
    image = ImageTk.PhotoImage(file="1.png")
    b.config(image=image)
    b.image = image
    b.pack()
make_button()
root.mainloop()

Why? The variables in make_button are local to that function. Same idea if you run into this type of problem inside a class.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...