Mohamed
Mohamed

Reputation: 65

tkinter GUI- label image not showing but is still there (kinda)

I'm trying to show a die at random to a tkinter GUI, but it does not work as expected.

from tkinter import *
from random import choice

def change_pic():

    die1 = PhotoImage(file=("dice-1.png"))
    die2 = PhotoImage(file=("dice-2.png"))
    die3 = PhotoImage(file=("dice-3.png"))
    die4 = PhotoImage(file=("dice-4.png"))
    die5 = PhotoImage(file=("dice-5.png"))
    die6 = PhotoImage(file=("dice-6.png"))

    faces=[die1, die2, die3, die4, die5, die6]
    label.config(image=choice(faces))
    label.grid(row=1, column=1)




root = Tk()

label = Label(root)
label.grid(row=1, column=1)


change_button  = Button(root, text="change", command =change_pic)
change_button.grid(row=1, column=2)
root.mainloop()

instead of showing the die image, it just show the place where it should be, and its size.

I tried a lot of things but I cannot fix it. please help.

Upvotes: 0

Views: 42

Answers (1)

figbeam
figbeam

Reputation: 7176

You choose the image for the label inside a function which puts the image in the function namespace. When the function ends the reference to the image is garbage collected.

You can fix this by saving a reference to the image in the label widget:

faces=[die1, die2, die3, die4, die5, die6]
img = choice(faces)
label.config(image=img)
label.image = img   # Save a reference to the image
label.grid(row=1, column=1)

Upvotes: 1

Related Questions