mardi 11 mai 2021

How to make image as a variable in python?

Is it possible to make images as a variable and use it for an argument? If I run the code, I don't get any error messages when I click my_button. The image does change or update every time but the text on my canvas does not update.

The Code when I run it

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



Aucun commentaire:

Enregistrer un commentaire