Snippets Collections
from customtkinter import *
import random
from PIL import Image

class Dice(CTk):
    def __init__(self):
        super().__init__()

        self.title("Dice Stimulator")

        # Getting images into CTk
        self.dice1 = CTkImage(light_image=Image.open("images/dice1.png"), size=(300,300))
        self.dice2 = CTkImage(light_image=Image.open("images/dice2.png"), size=(300,300))
        self.dice3 = CTkImage(light_image=Image.open("images/dice3.png"), size=(300,300))
        self.dice4 = CTkImage(light_image=Image.open("images/dice4.png"), size=(300,300))
        self.dice5 = CTkImage(light_image=Image.open("images/dice5.png"), size=(300,300))
        self.dice6 = CTkImage(light_image=Image.open("images/dice6.png"), size=(300,300))

        # putting them in a list for random choice
        self.image_list = [self.dice1, self.dice2, self.dice3, self.dice4, self.dice5, self.dice6]
        # Information
        label = CTkLabel(self, text="press enter or click the button")
        label.grid(row=0, padx=10, pady=10)
        # Button to roll the dice
        btn = CTkButton(self, text="Roll The Dice", command=self.roll)
        btn.grid(row=2, padx=10, pady=10)
        # Connecting button to the enter key
        self.bind("<Return>", lambda event: btn.invoke())

    def roll(self):
        # choosing a random die face
        img = random.choice(self.image_list)
        # displaying it on the label
        self.label = CTkLabel(self, text="", image=img)
        self.label.grid(row=1, padx=10, pady=10)

if __name__ == "__main__":
    app = Dice()
    app.mainloop()
star

Wed Jul 19 2023 14:51:05 GMT+0000 (Coordinated Universal Time) https://python-hub.com/day-5-dice-stimulator-python-ctk-gui/

#python #python-hub #day5

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension