如何用Python Tkinter时钟制作倒数计时器?

时间:2018-01-04 21:27:52

标签: python python-3.x tkinter clock countdowntimer

我的问题是如何配置这个基本时钟代码,使其从特定时间(如48小时)向后(或向下)计数,而不是像现在一样向常规时钟计数。

import tkinter as tk
import time
class App():

    def __init__(self):
        self.root = tk.Tk()
        self.label = tk.Label(text="")
        self.label.pack()
        self.update_clock()
        self.root.mainloop

    def update_clock(self):
        now = time.strftime("%H:%M:%S")
        self.label.configure(text=now)
        self.root.after(1000, self.update_clock)

app=App()

1 个答案:

答案 0 :(得分:0)

下面是一个类CountdowLabel,它需要几秒钟作为输入并开始倒计时并立即显示剩余时间:

import tkinter as tk
import datetime as dt


class CountdownLabel(tk.Label):
    """ A Label in the format of HH:MM:SS, that displays counting down from given 
    seconds.
    """

    def __init__(self, master, seconds_left):
        super().__init__(master)
        self._seconds_left = seconds_left
        self._timer_on = False
        self._countdown()                   # Start counting down immediately

    def _start_countdown(self):
        self._stop_countdown()
        self._countdown()

    def _stop_countdown(self):
        if self._timer_on:
            self.after_cancel(self._timer_on)
            self._timer_on = False

    def _countdown(self):
        self['text'] = self._get_timedelta_from_seconds(self._seconds_left)
        if self._seconds_left:
            self._seconds_left -= 1
            self._timer_on = self.after(1000, self._countdown)

    @staticmethod
    def _get_timedelta_from_seconds(seconds):
        return dt.timedelta(seconds=seconds)


if __name__ == '__main__':
    root = tk.Tk()

    countdown = CountdownLabel(root, 3)
    countdown.pack()

    root.mainloop()

下面是一个类Countdown,它从条目输入数秒,并在按下"Start"按钮时开始倒计时,同时显示标签上剩余的时间。要将秒数转换为时间格式this answer,并重置计时器this answer非常有用。

import tkinter as tk
import datetime

class Countdown(tk.Frame):
    '''A Frame with label to show the time left, an entry to input the seconds to count
    down from, and a start button to start counting down.'''
    def __init__(self, master):
        super().__init__(master)
        self.create_widgets()
        self.show_widgets()
        self.seconds_left = 0
        self._timer_on = False

    def show_widgets(self):

        self.label.pack()
        self.entry.pack()
        self.start.pack()

    def create_widgets(self):

        self.label = tk.Label(self, text="00:00:00")
        self.entry = tk.Entry(self, justify='center')
        self.entry.focus_set()
        self.start = tk.Button(self, text="Start", command=self.start_button)

    def countdown(self):
        '''Update label based on the time left.'''
        self.label['text'] = self.convert_seconds_left_to_time()

        if self.seconds_left:
            self.seconds_left -= 1
            self._timer_on = self.after(1000, self.countdown)
        else:
            self._timer_on = False

    def start_button(self):
        '''Start counting down.'''
        self.seconds_left = int(self.entry.get())   # 1. to fetch the seconds
        self.stop_timer()                           # 2. to prevent having multiple
        self.countdown()                            #    timers at once

    def stop_timer(self):
        '''Stops after schedule from executing.'''
        if self._timer_on:
            self.after_cancel(self._timer_on)
            self._timer_on = False

    def convert_seconds_left_to_time(self):

        return datetime.timedelta(seconds=self.seconds_left)


if __name__ == '__main__':
    root = tk.Tk()
    root.resizable(False, False)

    countdown = Countdown(root)
    countdown.pack()

    root.mainloop()