nitin sharma
nitin sharma

Reputation: 11

I am trying to create a rolling dice in python using tkinter

i am not able to create a rolling dice in python using tkinter. I want to create an effect of a rolling dice using a loop but it is not working , it just get freeze for some time and then give the output.

from tkinter import *
import random
import time

root =Tk()

def dice():


    num=["\u2680","\u2681","\u2682","\u2683","\u2684","\u2685"]

    roll=f'{random.choice(num)}'
    for i in range(20):
    
        dice_label.config(text=roll)
        
        time.sleep(0.5)
        root.update()
    


welcome_label= Label(root, text="Welcome to Dice Roll")
welcome_label.grid(row=0,column=0)
dice_label=Label(root,font=("Helvitica",300,"bold"),text="")
dice_label.grid(row=1,column=0)

button= Button(root,text="Click to Roll",padx=50, command=dice)
button.grid(row=2,column=0)

root.mainloop()

Upvotes: 1

Views: 379

Answers (2)

user15801675
user15801675

Reputation:

Here is your script with after. for/while loops mess with the mainloop. Hence, you should not use them or run them on a separate thread. Similarly, time.sleep() suspends the execution of the mainloop

from tkinter import *
import random
import time

root =Tk()
num2 =0
def dice():
    global num2
    if num2!=20:

        num=["\u2680","\u2681","\u2682","\u2683","\u2684","\u2685"]

        roll=f'{random.choice(num)}'

        dice_label.config(text=roll)

        num2+=1
        root.after(500,dice)
    else:
        num2=0
    
    


welcome_label= Label(root, text="Welcome to Dice Roll")
welcome_label.grid(row=0,column=0)
dice_label=Label(root,font=("Helvitica",300,"bold"),text="")
dice_label.grid(row=1,column=0)

button= Button(root,text="Click to Roll",padx=50, command=dice)
button.grid(row=2,column=0)

root.mainloop()

Upvotes: 1

TheLizzard
TheLizzard

Reputation: 7680

Same as @Sujay's answer but without the global variable:

import tkinter as tk
import random

# The 0 here is the default value
def dice(num2=0):
    if num2 < 20:

        num=["\u2680", "\u2681", "\u2682", "\u2683", "\u2684", "\u2685"]

        roll=str(random.choice(num))
        dice_label.config(text=roll)

        # After 500ms call `dice` again but with `num2+1` as it's argument
        root.after(500, dice, num2+1)
    

root = tk.Tk()

welcome_label = tk.Label(root, text="Welcome to Dice Roll")
welcome_label.grid(row=0, column=0)

dice_label = tk.Label(root, font=("Helvitica", 300, "bold"), text="")
dice_label.grid(row=1, column=0)

button = tk.Button(root,text="Click to Roll", command=dice)
button.grid(row=2,column=0)

root.mainloop()

Upvotes: 1

Related Questions