我如何让 time.sleep() 与 tkinter 一起工作?

编程入门 行业动态 更新时间:2024-10-24 14:19:34
本文介绍了我如何让 time.sleep() 与 tkinter 一起工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试定期在屏幕上显示一系列数字.

I'm trying to show a sequence of numbers on the screen at regular intervals.

我是 python 新手,所以这可能很明显,但我尝试过 .afterpygame.time.wait,但都没有奏效.

I'm new to python so it may be something obvious but I have tried .after and pygame.time.wait, but neither worked.

这是代码:

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

推荐答案

我假设您想显示新号码代替旧号码,而不是在旧号码下方.

I assume you want to show new number in place of old number, not below it.

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

这篇关于我如何让 time.sleep() 与 tkinter 一起工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 12:15:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1393548.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:工作   time   sleep   tkinter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!