基本的Tkinter倒数计时器 [英] Basic Tkinter countdown timer

查看:259
本文介绍了基本的Tkinter倒数计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在从事一个项目,该项目需要非常简单的倒数计时器,并且可以在tkinter GUI中使用,并且不依赖于递归。我尝试了不同的方法,但到目前为止似乎无济于事。

I am currently working on a project that requires are very simple countdown timer, that works in the tkinter GUI and that dosen't rely on a recursion. I have tried different things but nothing seems to work so far.

import time
from tkinter import *


root = Tk()
root.title("Timer")
root.geometry("100x100")

def countdown(count):
    label = Label(root, text= count)
    label.place(x=35, y=15)

for i in range(5,0,-1):
    countdown(i)
    time.sleep(1)

root.mainloop()


推荐答案

您不能使用 sleep ,因为它会停止 mainloop 且程序无法运行。您可以使用 root.after 在1000ms(1s)之后调用函数

You can't use sleep because it stops mainloop and program can't work. You can use root.after to call function after 1000ms (1s)

import tkinter as tk

def countdown(count):
    # change text in label        
    label['text'] = count

    if count > 0:
        # call countdown again after 1000ms (1s)
        root.after(1000, countdown, count-1)

root = tk.Tk()

label = tk.Label(root)
label.place(x=35, y=15)

# call countdown first time    
countdown(5)
# root.after(0, countdown, 5)

root.mainloop()

这篇关于基本的Tkinter倒数计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆