Dice Simulator GUI project (code) in Python

← Back to Projects

Dice Simulator GUI in Python.

About the project: This is a Dice roll Simulator with a Graphical User Interface (GUI).

For this project, we shall use Python's built-in tkinter library, which is a standard GUI toolkit.

This will allow us to create a window with a button and a display area for the dice roll, making it more interactive than a text-based application.

How to use this program:

Run the Python script.

When you run it, a small window will appear with a "Roll Dice" button.

Clicking this button will generate a random number between 1 and 6 and display it prominently in the window.

This Python script creates a simple GUI application.

Since tkinter is a standard library, you should not need to install anything extra. Enjoy your dice rolling


Project Level: Beginner

You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.

Steps: Follow these steps

Step 1: Copy below code using green 'copy' button.

Step 2: Paste the code on your chosen editor.

Step 3: Save the code with filename and .py extention.

Step 4: Run (Press F5 if using python IDLE)




# dice_simulator_gui.py

import tkinter as tk
import random

def roll_dice():
    """
    Generates a random number between 1 and 6 (inclusive)
    and updates the label with the result.
    """
    # Generate a random number between 1 and 6
    dice_roll = random.randint(1, 6)
    
    # Update the text of the dice_label
    dice_label.config(text=str(dice_roll))

def main():
    """
    Main function to set up and run the Dice Simulator GUI.
    """
    # Create the main window
    global window
    window = tk.Tk()
    window.title("Dice Simulator")
    window.geometry("300x200") # Set initial window size
    window.resizable(False, False) # Prevent resizing for simplicity

    # Configure grid for centering
    window.grid_rowconfigure(0, weight=1)
    window.grid_rowconfigure(1, weight=1)
    window.grid_columnconfigure(0, weight=1)

    # Create a label to display the dice roll
    global dice_label
    dice_label = tk.Label(
        window,
        text="Roll!",
        font=("Arial", 48), # Large font for the dice number
        pady=20 # Add some vertical padding
    )
    dice_label.grid(row=0, column=0, pady=10) # Place label in the grid

    # Create a button to roll the dice
    roll_button = tk.Button(
        window,
        text="Roll Dice",
        command=roll_dice, # Link the button to the roll_dice function
        font=("Arial", 16),
        bg="#4CAF50", # Green background
        fg="white",   # White text
        activebackground="#45a049" # Darker green when pressed
    )
    roll_button.grid(row=1, column=0, pady=10) # Place button in the grid

    # Start the Tkinter event loop
    window.mainloop()

# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
    main()