基本的 Tkinter 倒数计时器

Eld*_*dge 3 python tkinter timer countdown

我目前正在开发一个需要非常简单的倒数计时器的项目,它在 tkinter GUI 中工作并且不依赖于递归。我尝试了不同的东西,但到目前为止似乎没有任何效果。

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()
Run Code Online (Sandbox Code Playgroud)

fur*_*ras 8

您无法使用,sleep因为它停止mainloop并且程序无法运行。您可以root.after在 1000 毫秒(1 秒)后使用调用函数

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()
Run Code Online (Sandbox Code Playgroud)