簡體   English   中英

tkinter GUI-標簽圖像未顯示但仍在那里(有點)

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

我正在嘗試向tkinter GUI隨機顯示一個模具,但是它沒有按預期工作。

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()
  • 這是我的代碼

而不是顯示模具圖像,它只是顯示應該放置的位置及其大小。

我做了很多嘗試,但無法解決。 請幫忙。

您可以在函數內為標簽選擇圖像,該圖像會將圖像放入函數名稱空間中。 函數結束時,將對圖像的引用進行垃圾回收。

您可以通過在標簽小部件中保存對圖像的引用來解決此問題:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM