jeudi 7 octobre 2021

How can I add a 2D cycling animation to a simple roll-the-dice program in Python?

I basically went through one of those practice coding projects and all the code below is essentially from there, with a minor few tweaks.

I would like to add to this program a running cycle of all possible outcomes of the die for 2-3 seconds before the outcome is displayed. How would I go about doing this? I assume I'm going to have to import the time module to say I want the images to cycle for 2 or 3 seconds after the button is clicked but before the outcome is displayed, but that is as far as I've gotten.

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

Dies = '/Users/rumham/Documents/dice'

# main window of application w buttons labels images
root = Tk()
root.geometry('600x600')
root.title('Roll the dice')


# add labels giving a heading and image and random number
# label for the frame
blankline = Label(root, text="")
blankline.pack()

# label w different font n formatting
headinglabel = Label(root, text="Heyyo rollin dice",
    fg = 'light green',
    bg = 'dark green',
    font = "Helvetica 16 bold italic")
headinglabel.pack()

#images
dice = ['die1.jpeg','die2.jpeg','die3.jpeg','die4.jpeg','die5.jpeg','die6.jpeg']

# #random
dice_img_0 = Image.open(os.path.join(Dies, random.choice(dice)))
dice_img_0 = dice_img_0.resize((400,400), Image.ANTIALIAS)
dice_img = ImageTk.PhotoImage(dice_img_0)


# label widget for image
image_label = Label(root, image=dice_img)
image_label.image = dice_img

# packing widget in the parent widget
image_label.pack(expand=True)

# function activated by button
def rolling_dice():
    # dice_img = ImageTk.PhotoImage(Image.open(random.choice(dice)))
    dice_img_0 = Image.open(os.path.join(Dies, random.choice(dice)))
    dice_img_0 = dice_img_0.resize((400,400), Image.ANTIALIAS)
    dice_img = ImageTk.PhotoImage(dice_img_0)
    #update img
    image_label.configure(image=dice_img)
    #keep a reference
    image_label.image = dice_img


# adding button and command will call rolling_dice function
button = Button(root, text='roll the dice', fg='blue', command=rolling_dice)

# pack widget into parent widget
button.pack(expand=True)


# call mainloop of Tk
# keeps window open
root.mainloop()

Everything runs perfectly, I would really just like to add the 2-3 second image cycle as well, simulating rolling dice but obviously in 2D just cycling through all 6 images. Any help is greatly appreciated.




Aucun commentaire:

Enregistrer un commentaire