|
| 1 | +import tkinter as tk |
| 2 | +from PIL import Image, ImageTk |
| 3 | +import random |
| 4 | +import time |
| 5 | +import os |
| 6 | + |
| 7 | +# Initialize the Tkinter window |
| 8 | +window = tk.Tk() |
| 9 | +window.geometry("500x360") |
| 10 | +window.title("Dice Roll") |
| 11 | +window.configure(bg='black') |
| 12 | + |
| 13 | +# Define a list of dice images |
| 14 | +dice = ["dice_1.png", "dice_2.png", "dice_3.png", "dice_4.png", "dice_5.png", "dice_6.png"] |
| 15 | + |
| 16 | +# Verify that all dice images exist |
| 17 | +for dice_image in dice: |
| 18 | + if not os.path.exists(dice_image): |
| 19 | + print(f"Error: {dice_image} not found.") |
| 20 | + exit() |
| 21 | + |
| 22 | +# Define a list of colors for the animation |
| 23 | +colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'pink'] |
| 24 | + |
| 25 | +# Choose a random image for each dice and display them initially on the window |
| 26 | +image1 = ImageTk.PhotoImage(Image.open(random.choice(dice))) |
| 27 | +image2 = ImageTk.PhotoImage(Image.open(random.choice(dice))) |
| 28 | +label1 = tk.Label(window, image=image1, bg='black') |
| 29 | +label2 = tk.Label(window, image=image2, bg='black') |
| 30 | +label1.image = image1 |
| 31 | +label2.image = image2 |
| 32 | +label1.place(x=40, y=100) |
| 33 | +label2.place(x=900, y=100) |
| 34 | + |
| 35 | +# Define a function named "dice_roll" with animation |
| 36 | +def dice_roll(): |
| 37 | + for _ in range(10): # Number of frames in the animation |
| 38 | + color = random.choice(colors) # Choose a random color for the background |
| 39 | + image1 = ImageTk.PhotoImage(Image.open(random.choice(dice))) |
| 40 | + label1.configure(image=image1, bg=color) |
| 41 | + label1.image = image1 |
| 42 | + image2 = ImageTk.PhotoImage(Image.open(random.choice(dice))) |
| 43 | + label2.configure(image=image2, bg=color) |
| 44 | + label2.image = image2 |
| 45 | + window.update() # Update the window to show changes |
| 46 | + time.sleep(0.1) # Pause to create animation effect |
| 47 | + # Set the final images and background to black after animation |
| 48 | + image1 = ImageTk.PhotoImage(Image.open(random.choice(dice))) |
| 49 | + label1.configure(image=image1, bg='black') |
| 50 | + label1.image = image1 |
| 51 | + image2 = ImageTk.PhotoImage(Image.open(random.choice(dice))) |
| 52 | + label2.configure(image=image2, bg='black') |
| 53 | + label2.image = image2 |
| 54 | + |
| 55 | +# Define a button widget labeled "ROLL" with green background and white text, positioned at the top of the window |
| 56 | +button = tk.Button(window, text="ROLL", bg="green", fg="white", font="Times 20 bold", command=dice_roll) |
| 57 | +button.place(x=660, y=10) |
| 58 | + |
| 59 | +# Display the Tkinter window and wait for user interaction |
| 60 | +window.mainloop() |
0 commit comments