簡體   English   中英

如何在 tkinter 中進行簡單的倒計時?

[英]How do I make a simple countdown time in tkinter?

我正在幾分鍾內制作一個簡單的倒數計時器。 我似乎無法在文本標簽中顯示倒計時。 有人能幫我嗎?

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

首先,而不是使用這個

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

此外,我建議使用線程,以便在程序運行時能夠使用其他按鈕。

請求的代碼:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM