首页 > 解决方案 > 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.

标签: python-3.xtkinter

解决方案


您为函数内的标签选择图像,该函数将图像放在函数命名空间中。当函数结束时,对图像的引用被垃圾收集。

您可以通过在标签小部件中保存对图像的引用来解决此问题:

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)

推荐阅读