我正在尝试使用tkinter在python中创建一个滚动骰子

2024-04-29 11:55:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我无法使用tkinter在python中创建滚动骰子。我想创建一个使用循环滚动骰子的效果,但它不起作用,它只是冻结了一段时间,然后给出输出

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()

Tags: textimporttimetkintercolumnrandomroot骰子
2条回答

这是带有after的脚本for/while循环与mainloop相混淆。因此,您不应该使用它们或在单独的线程上运行它们。类似地,time.sleep()暂停执行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()

与@Sujay的答案相同,但没有全局变量:

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()

相关问题 更多 >