Dice Rolling Simulator Python Game [Source Code Included]
Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python
Snake and Ladders, Ludo and Checkers, are the most favorite games of all time. But, it feels terrible when you drop the plan of playing just because you couldn’t find the dice. So, here is a fascinating option to give you a chance to make something cool. Let’s build a Dice Rolling Simulator with basic knowledge of Python.
What is Tkinter?
Python offers various packages to design the GUI, i.e. the Graphical User Interface. Tkinter is the most common, fast, and easy to use Python package used to build Graphical User Interface applications. It provides a powerful Object-Oriented Interface and is easy to use. Also, you develop an application; you can use it on any platform, which reduces the need of amendments required to use an app on Windows, Mac, or Linux.
Dice Rolling Simulator in Python
We all know about dice. It’s a simple cube with numbers from 1 to 6 written on its face. But what is simulation? It is making a computer model. Thus, a dice simulator is a simple computer model that can roll a dice for us.
We aim to build a dice simulator which looks like:
Download Dice Rolling Simulator Project Code
Before proceeding ahead, please download the source code of dice rolling simulator python project: Dice Rolling Simulator Project
Build Dice Rolling Simulator
Step 1: Importing the required modules
We will import the following modules:
- Tkinter: Imported to use Tkinter and make GUI applications.
- Image, Imagetk: Imported from PIL, i.e. Python Imaging Library. We use it to perform operations involving images in our UI.
- Random: Imported to generate random numbers.
Code:
import tkinter from PIL import Image, ImageTk import random
Step 2: Building a top-level widget to make the main window for our application
In this step, we will build the main window of our application, where the buttons, labels, and images will reside. We also give it a title by title() function.
Code:
# top-level widget which represents the main window of an application root = tkinter.Tk() root.geometry('400x400') root.title('DataFlair Roll the Dice')
Explanation:
The above code sets the title of the application window as ‘DataFlair Roll the Dice’. Running the above code will generate a blank window of dice rolling simulator python project with the title on it.
Step 3: Designing the buttons
Now, just think, what we need to roll a die? Just our hands!
The below code will add a label giving a heading to our dice simulator. Also, we will add an image area, which will display the image chosen by random numbers.
Code:
# Adding label into the frame BlankLine = tkinter.Label(root, text="") BlankLine.pack() # adding label with different font and formatting HeadingLabel = tkinter.Label(root, text="Hello from DataFlair!", fg = "light green", bg = "dark green", font = "Helvetica 16 bold italic") HeadingLabel.pack() # images dice = ['die1.png', 'die2.png', 'die3.png', 'die4.png', 'die5.png', 'die6.png'] # simulating the dice with random numbers between # 0 to 6 and generating image DiceImage = ImageTk.PhotoImage(Image.open(random.choice(dice))) # construct a label widget for image ImageLabel = tkinter.Label(root, image=DiceImage) ImageLabel.image = DiceImage # packing a widget in the parent widget ImageLabel.pack( expand=True)
Explanation:
Here, we use pack() to arrange our widgets in row and column form. The ‘BlankLine’ label is to skip a line, whereas we use ‘HeadingLabel’ label to give a heading.
- root – the name by which we refer to the main window of the application
- text – text to be displayed in the HeadingLabel
- fg– the colour of the font used in HeadingLabel
- bg – background colour of the HeadingLabel
- font – used to give customised fonts to the HeadingLabel text
- .pack() – Used to pack the widget onto the root window
Step 4: Forming a list of images to be randomly displayed
Code:
# images dice = ['die1.png', 'die2.png', 'die3.png', 'die4.png', 'die5.png', 'die6.png'] # simulating the dice with random numbers between # 0 to 6 and generating image DiceImage = ImageTk.PhotoImage(Image.open(random.choice(dice)))
Explanation:
‘dice’ is the list of names of images kept in same folder, which are chosen randomly according to the random number generated.
‘DiceImage’ is used to store an image of dice which is chosen by randomly generated numbers.
Step 5: Constructing a label for image, adding a button and assigning functionality
Code:
# construct a label widget for image ImageLabel = tkinter.Label(root, image=DiceImage) ImageLabel.image = DiceImage # packing a widget in the parent widget ImageLabel.pack( expand=True) # function activated by button def rolling_dice(): DiceImage = ImageTk.PhotoImage(Image.open(random.choice(dice))) # update image ImageLabel.configure(image=DiceImage) # keep a reference ImageLabel.image = DiceImage # adding button, and command will use rolling_dice function button = tkinter.Button(root, text='Roll the Dice', fg='blue', command=rolling_dice) # pack a widget in the parent widget button.pack( expand=True)
Explanation:
‘ImageLabel’ is to place an image in the window. The parameter expands declared as True so that even if we resize the window, image remains in the center.
Major function:
‘rolling_dice’ function is a function that is executed every time a button is clicked. This is attained through the ‘command=rolling_dice’ parameter while defining a button.
Step 6: Forming a list of images to be randomly displayed
Code:
# call the mainloop of Tk # keeps window open root.mainloop()
Explanation:
‘root.mainloop()’ is used to open the main window. It acts as the main function of our program.
Dice Rolling Simulator Python Output
Conclusion
Yay! We have successfully developed a cool application – Dice Rolling Simulator in Python. Now, you can just click on a button and get your next number. Cheers to Python and its package ‘Tkinter’ which supports functions and makes our work easy. Who would have thought that we can develop an application by only the ‘random’ function of python? As of now, we have an understanding of Python, Tkinter, and random function.
Did we exceed your expectations?
If Yes, share your valuable feedback on Google
Need some explanation for Freshers on projects
In this project we have stored six images in a list named dice and we are picking a random image everytime user clicks on ‘Roll the dice’ button. You can learn more about GUI from our site: https://data-flair.training/blogs/python-gui-programming/
I want more information about project.
Such as frant end , back end and all aothe information need to define the type of project
We have used python for both front end as well as backend. We have created the GUI using tkinter.
We have used python for both front end as well as backend. We have created the GUI using tkinter.
Hi! Can you send my a picture with all the project, please! I don’t know where a should save the pictures 🙁 in a folder? inside de project?
save the images in the project folder itself (where the source code file is present).
Could you help me understand the two lines below:
ImageLabel.configure(image = DiceImage)
ImageLabel.image = DiceImage
I do not understand why we need to redefine the ‘image’ by ‘DiceImage’ twice?
Garbage collector in tkinter destroys image if reference isn’t saved. Therefore we are saving it as an attribute to the widget.
# construct a label widget for image
ImageLabel = tkinter.Label(root, image=DiceImage)
ImageLabel.image = DiceImage
The code at this line gives an error since the error arises because
the button that calls the function is itself sitting in an active window that is also running as Tkinter.Tk().
We are just ensuring that the garbage collector doesn’t destroy the image
Info isn’t enough for making could you please help for knowing more about the project details
You must know about random function and python GUI to understand this project. You can learn about python GUI from our site: https://data-flair.training/blogs/python-gui-programming/
It hv error, why? down list:
File “d:\VScode\Python\dice-rolling-simulator-python-code\Data flair dice.py”, line 23, in
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
File “C:\Users\jlian\AppData\Local\Programs\Python\Python39\lib\site-packages\PIL\Image.py”, line 2904, in open
fp = builtins.open(filename, “rb”)
FileNotFoundError: [Errno 2] No such file or directory: ‘die6.png’
Please keep the image files in the same directory where you kept the source code. You can download the same along the source code from downloads section
can you explain please that what does it mean that you are saying about keeping the image, which image are you talking about
To create the dice rolling simulator we required a dice image . Below are the steps to upload the image in your editor directory
Download the dice image from the above source code
Open your preferred Integrated Development Environment (IDE)
Locate idle directory or path
Copy the dice image from your computer storage
Then simply paste your copied image in your (IDE) path or directory.
“C:\Users\Harel Cohen\AppData\Local\Programs\Python\Python39\python.exe” “C:/Users/Harel Cohen/PycharmProjects/pythonProject/Dice_Rolling_Simulator.py”
Traceback (most recent call last):
File “C:\Users\Harel Cohen\PycharmProjects\pythonProject\Dice_Rolling_Simulator.py”, line 26, in
DiceImage = PhotoImage(Image.open(random.choice(dice)))
File “C:\Users\Harel Cohen\AppData\Local\Programs\Python\Python39\lib\site-packages\PIL\Image.py”, line 2975, in open
fp = builtins.open(filename, “rb”)
FileNotFoundError: [Errno 2] No such file or directory: ‘dice3.png’
Process finished with exit code 1
This error commonly occurs when your idle terminal does not contain any file. To fix this issue, you can resolve it by downloading the dice image, pasting it into your idle directory, and then running your code again.
Explain about to upload dice image in dice list
save it in C:/user/Vivek/
[Vivek in my case]
I hava an error
Traceback (most recent call last):
File “c:\PYTHON\project\dice_rolling.py”, line 10, in
BlankLine = tkinter.Label(root, text=””)
File “C:\Users\vivekdeep408\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py”, line 3177, in __init__
Widget.__init__(self, master, ‘label’, cnf, kw)
File “C:\Users\vivekdeep408\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py”, line 2601, in __init__
self.tk.call(
_tkinter.TclError: can’t invoke “label” command: application has been destroyed
can you please send the images link