0
import tkinter as tk
from tkinter import ttk

root = tk.Tk()

def change():
    img2 = tk.PhotoImage(file = "img2.png")
    label.configure(image = img2)

img1 = tk.PhotoImage(file = "img1.png")

label = ttk.Label(root, image = img1)
label.place(x = 0, y = 0)

button = ttk.Button(root, text = "Change", command = change)
button.place(x = 20, y = 20)

This is my current code which has a button to change one image to another. The first image displays normally, however when the button is pressed tkinter just reverts to it's usual background. Please help this is driving me crazy

New contributor
Ingrid Ledingham is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
2
  • Do you have a tk.mainloop() btw? Commented Nov 23 at 20:13
  • yeah just forgot to put it here Commented Nov 23 at 20:31

1 Answer 1

1

If the image object runs out of references (like when your callback returns and img2 is destroyed), the image is wiped too:

When the last Python reference to the image object is deleted, the image data is deleted as well, and Tk will display an empty box wherever the image was used.

Move img2 = out of the function to make it a global so it isn't destroyed when the functions exits.

Sign up to request clarification or add additional context in comments.

1 Comment

The issue you're experiencing is due to Python's garbage collection. When the change() function finishes executing, the img2 variable goes out of scope and gets garbage collected, which causes the image to disappear from the label.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.