Dice Rolling Simulator in Python
We will be creating a GUI, where you can roll your Dice. Excited?? Yeah me too!! So, let’s begin.
You can find the entire code here! But let’s first learn how and what to do.
1. Import random and tkinter
First, we need to import random and tkinter (to create a GUI). We will be generating a random number on our dice, after all that’s what the Dice game is all about, some random luck :|
import random
from tkinter import *
2. Create a tkinter GUI instance
root = Tk()
Also, define the geometry, let’s say,
root.geometry("700x450") #(lengthxbreadth)
Our GUI will have two important components, the button which will trigger the rolling of Dice and the Dice label.
3. Create Dice Label
label = tkinter.Label(root,font=('Helvetica', 260))#The 3 parameters are: GUI instance, font and font size
This is to create a widget where we can place our button. Read this, to know more.
Feel free to modify the GUI and font sizes :)
4. Create a Button
button = tkinter.Button(root, text='Roll Dice', foreground='blue', command=roll)
Now let’s place the button in the top center, so that it looks good ;)
button.place(x=325,y=10)
5. Let’s write a function to display random numbers on our Dice
def roll():
dice = ['\u2680', '\u2681', '\u2682', '\u2683', '\u2684', '\u2685']
label1.configure(text=f'{random.choice(dice)} {random.choice(dice)}')
label1.pack()
6. We are Done!!
Let’s close the GUI instace and run our python code.
This is how you are supposed to close the instance,
root.mainloop()
Hope it worked for you and you enjoyed it. If not then don’t worry, go to my repo, and cross check with my code. It’s very simple and I hope you are happy with your brand new Dice’s.
TIP: If you don’t want to roll 2 dices, or want to roll more than 2, then, modify the label1.config() instruction accordingly.