python-3.x - 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()
- this is my code
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.
解决方案
您为函数内的标签选择图像,该函数将图像放在函数命名空间中。当函数结束时,对图像的引用被垃圾收集。
您可以通过在标签小部件中保存对图像的引用来解决此问题:
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)
推荐阅读
- c# - 如何在使用 Prism 的 MVVM 应用程序中每次选择 TabItem 时运行方法
- php - 当 Web 服务器的 mysql 数据库发生变化时,我想发送推送通知。可能吗?
- ruby - Ruby 如何解决 'diamond' mixin 中的方法查找问题?
- asp.net - RadioButtonList 1 行彩色
- javascript - onclick="$('#id').toggle()" 不起作用,需要为 Chrome 旧版本重写
- java - 是否存在在没有 GC 的情况下使用的堆内存减少的情况,即没有 GC 事件的情况?
- php - 何时使用 MailChimp 单一或批量操作?
- java - 构造函数中带有@Value的FactoryBean?
- java - How to save path drawn on canvas as png
- mysql - mySQL:如何编写满足两个或多个条件的查询