扔骰子模拟器,模拟扔骰子。
代码:
import os
import tkinter as tk
from PIL import Image, ImageTk
import random
WIDTH = 500
HEIGHT = 320
class DiceRollSimulator:
def __init__(self, master):
self.master = master
self.master.geometry(f"{WIDTH}x{HEIGHT}")
self.master.title("Dice Roll Simulator")
pictures_path = os.path.join(os.path.dirname(__file__), 'pictures')
self.dice_images = [
ImageTk.PhotoImage(Image.open(os.path.join(pictures_path, f'dice_{i}.png')))
for i in range(1, 7)
]
self.label = tk.Label(self.master, image=self.dice_images[0])
self.label.pack(pady=20)
self.roll_button = tk.Button(self.master, text="Roll Dice", command=self.roll_dice)
self.roll_button.pack()
def roll_dice(self):
result = random.randint(1, 6)
self.label.config(image=self.dice_images[result - 1])
if __name__ == "__main__":
root = tk.Tk()
app = DiceRollSimulator(root)
root.mainloop()
截图:
演示:
扔骰子模拟器演示视频
改进:
如果可以看到立体的骰子被扔出去旋转的过程,体验将会更加逼真。