How to add image to widget? Why is the image not displayed?

How to add image to widget in tkinter?

Why, when I use this code, it does not work:

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

but does it work ?:

an_image=PhotoImage(file="test.png")
some_widget.config(image=anImage, compound=RIGHT)
+4
source share
1 answer

Your image receives garbage collection when you try to use it in the first version.

effbot is ancient, but here's a nice snippet :

You must store the 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 announced globally.

, , ,

:

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()

:

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()

? make_button . , .

+6