如何在python中将图像作为变量?

How to make image as a variable in python?

是否可以将图像作为变量并将其用作参数?如果我 运行 代码,我在单击 my_button 时不会收到任何错误消息。图片确实每次都会更改或更新,但我 canvas 上的文字不会更新。

from tkinter import *
from PIL import Image, ImageTk
import random


root = Tk()
root.geometry('700x700')
root.title('Dice Rolling Simulation')

bg = PhotoImage(file ="bg.png")
label = Label(root, image=bg)
label.place(x=0, y=0, relwidth =1, relheight = 1)



l0 = Label(root, text="")
l0.pack()

l1 = Label(root, text="DICE SIMULATOR", fg="white",
               bg='#000009',
               font="Helvetica 30 bold italic")
l1.pack()
#images
d1 = 'die1.png'
d2 = 'die2.png'
d3 = 'die3.png'
d4 = 'die4.png'
d5 = 'die5.png'
d6 = 'die5.png'

dice = [d1, d2, d3 ,d4 ,d5, d6]
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
label1 =Label(root, image=image1)
label1.image = image1
label1.pack(expand=True)

global result
canvas= Canvas(root, width = 200, height = 50, bg = "red")
canvas.pack(pady = 5)
result = canvas.create_text(100,25, font = ('Helvetica', 24), text = "ONE")

def rolling_dice():
    image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
    label1.configure(image=image1)
    label1.image = image1
    if image1 == d1:
        canvas.itemconfig(result, text = "ONE")
    elif image1 == d2:
       canvas.itemconfig(result, text="TWO")
elif image1 == d3:
    canvas.itemconfig(result, text="THREE")

elif image1 == d4:
    canvas.itemconfig(result, text="FOUR")
elif image1 == d5:
    canvas.itemconfig(result, text="FIVE")
elif image1 ==d6:
    canvas.itemconfig(result, text="SIX")


my_button = Button(root, text = "ROLL THE DICE", command = rolling_dice, font = ("Helvetica",24), 
 fg="blue")
my_button.pack(pady=20)

root.mainloop()

您需要将random.choice(dice)的结果保存在rolling_dice()中,然后使用此结果更新图像和文本,而不是使用image1:

def rolling_dice():
    choice = random.choice(dice)
    image1 = ImageTk.PhotoImage(Image.open(choice))
    label1.configure(image=image1)
    label1.image = image1
    if choice == d1:
        canvas.itemconfig(result, text = "ONE")
    elif choice == d2:
       canvas.itemconfig(result, text="TWO")
    elif choice == d3:
        canvas.itemconfig(result, text="THREE")
    elif choice == d4:
        canvas.itemconfig(result, text="FOUR")
    elif choice == d5:
        canvas.itemconfig(result, text="FIVE")
    elif choice ==d6:
        canvas.itemconfig(result, text="SIX")

另一种简单的方法是获取一个0到5之间的随机数,并使用这个数来更新图像和文本:

def rolling_dice():
    idx = random.randrange(len(dice)) # random number between 0 and 5
    image1 = ImageTk.PhotoImage(Image.open(dice[idx]))
    label1.configure(image=image1)
    label1.image = image1
    number = ("ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX")
    canvas.itemconfigure(result, text=number[idx])