如何在tkinter中进行简单的倒计时?

问题描述 投票:-1回答:1

我在几分钟内做了一个简单的倒数计时器。我似乎无法在文本标签中显示倒计时。有人能帮我吗?

import tkinter as tk
import time

def countdown(t):
    while t:
        mins, secs = divmod(t, 60)
        timeformat = '{:02d}:{:02d}'.format(mins, secs)
        print(timeformat, end='\r')
        label.config(text=timeformat)
        time.sleep(1)
        t -= 1

root = tk.Tk()
label = tk.Label(root,text="Time")
label.pack()
button = tk.Button(root,text = "click here", command=countdown(60)).pack()

root.mainloop()
python tkinter
1个回答
0
投票

首先,而不是使用它

button = tk.Button(root,text = "click here", command=countdown(60)).pack()

你必须使用lambda来指定参数

button = tk.Button(root,text = "click here", command=lambda:countdown(60)).pack()

然后,每次更新标签时都必须更新root

def countdown(t):
while t:
    mins, secs = divmod(t, 60)
    timeformat = '{:02d}:{:02d}'.format(mins, secs)
    print(timeformat, end='\r')
    label.config(text=timeformat)
    root.update() #This way your program will display the numbers.
    time.sleep(1)
    t -= 1

另外,我建议使用Threads,以便在程序运行时使用其他按钮。

请求的代码:

import threading
import tkinter as tk
import time
import sys

runtime = 300 #In seconds, you can change this

class CountdownApp:
    def __init__(self, runtime):
        self.runtime = runtime
        self._createApp()
        self._packElements()
        self._startApp()

    def _createApp(self):
        self.root = tk.Tk()

    def _packElements(self):
        self.label = tk.Label(self.root,text="Time")
        self.label.pack()
        self.button = tk.Button(self.root,text = "click here", command=self.startCounter)
        self.button.pack()

    def countdown(self):
        self.t = self.runtime
        self.button.config(state='disabled')
        while self.t > -1:
            self.mins, self.secs = divmod(self.t, 60)
            self.timeformat = '{:02d}:{:02d}'.format(self.mins, self.secs)
            self.label.config(text=self.timeformat)
            self.root.update()
            time.sleep(1)
            self.t -= 1
        self.label.config(text='Time')
        self.root.update()
        self.button.config(state='normal')

    def startCounter(self):
        threading.Thread(target=self.countdown).start()

    def _startApp(self):
        self.root.mainloop()


CountdownApp(runtime)
© www.soinside.com 2019 - 2024. All rights reserved.