如何使time.sleep()与tkinter一起使用?

时间:2017-12-03 18:51:03

标签: python time tkinter

我试图定期在屏幕上显示一系列数字。

我是python的新手所以它可能是显而易见的,但我尝试了.afterpygame.time.wait,但都没有用。

这是代码:

from tkinter import*
from random import *
import time



my_list = []




def Create_NUM(event):
    x = 0

    for x in range(level + 2):
        button1.destroy()
        num = randint(1, 100)
        my_list.append(num)
        Label(root, text=num,fg="red").pack()
        one.pack()
        time.sleep(2)





root=Tk()

num = 0
level = 1
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)

button1 = Button(bottomFrame, text="Click to start game",fg="red")
button1.bind("<Button-1>", Create_NUM)
button1.pack()



root.mainloop()

2 个答案:

答案 0 :(得分:0)

我假设您想显示新号码而不是旧号码。

import tkinter as tk
import random

def start():
    # hide button
    button.pack_forget()
    # run `add_number` first time
    add_number(level+2)

def add_number(x):

    num = random.randint(1, 100)
    my_list.append(num)
    label['text'] = num

    if x > 0:
        # repeat after 2000ms (2s)
        root.after(2000, add_number, x-1)
    else:
        # show button again after the end
        button.pack()      

# --- main ---

my_list = []
level = 1

root = tk.Tk()

label = tk.Label(root)
label.pack()

button = tk.Button(root, text="Click to start game", command=start)
button.pack()

root.mainloop()

答案 1 :(得分:0)

只需在您的函数 root.update()

中使用这个简单的命令