Reputation: 29
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.
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()
Upvotes: 1
Views: 622
Reputation: 46669
You need to save the result of random.choice(dice)
inside rolling_dice()
, then use this result to update the image and text instead of using 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")
Another simple way is to get a random number between 0 and 5 and use this number to update the image and text:
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])
Upvotes: 2