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

如何在python中将图像设置为变量?,python,tkinter,canvas,random,Python,Tkinter,Canvas,Random,是否可以将图像作为变量并将其用作参数?如果我运行代码,当我单击my_按钮时,不会收到任何错误消息。图像每次都会更改或更新,但画布上的文本不会更新 您需要将random.choice(dice)的结果保存在rolling_dice()中,然后使用此结果更新图像和文本,而不是使用image1: def rolling_dice(): 选择=随机。选择(骰子) image1=ImageTk.PhotoImage(Image.open(选项)) 标签1.configure(image=image1)

是否可以将图像作为变量并将其用作参数?如果我运行代码,当我单击
my_按钮时,不会收到任何错误消息。图像每次都会更改或更新,但画布上的文本不会更新


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

def rolling_dice():
选择=随机。选择(骰子)
image1=ImageTk.PhotoImage(Image.open(选项))
标签1.configure(image=image1)
label1.image=image1
如果选项==d1:
canvas.itemconfig(结果,text=“一”)
elif选项==d2:
canvas.itemconfig(结果,text=“两个”)
elif选项==d3:
canvas.itemconfig(结果,text=“三”)
elif选项==d4:
canvas.itemconfig(结果,text=“四”)
elif选项==d5:
canvas.itemconfig(结果,text=“五”)
elif选项==d6:
canvas.itemconfig(结果,text=“六”)

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

def rolling_dice():
idx=random.randrange(len(dice))#0到5之间的随机数
image1=ImageTk.PhotoImage(Image.open(dice[idx]))
标签1.configure(image=image1)
label1.image=image1
数字=(“一”、“二”、“三”、“四”、“五”、“六”)
canvas.itemconfigure(结果,文本=编号[idx])

谢谢!
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()