How to make a pausable timer in python?

柔情痞子 提交于 2020-02-15 06:56:27

问题


I want to create a timer in python with the following functions:

timer.start() - should start the timer

timer.pause() - should pause the timer

timer.resume() - should resume the timer

timer.get() - should return the current time

The timer should run from 0 upwards. It is meant to measure time, not trigger a callback function.

So if you start it, it should start counting the seconds like 0 1 2 3, if you pause it, it should be stilll at 3, but not going further. After its resumed it then goes on with 4 5 6 and so on

How can I do this?


Pause/Resume functions for timer is not a duplicate because I do not care about callbacks.


回答1:


# mytimer.py
from datetime import datetime
import time

class MyTimer():
    """
    timer.start() - should start the timer
    timer.pause() - should pause the timer
    timer.resume() - should resume the timer
    timer.get() - should return the current time
    """

    def __init__(self):
        print('Initializing timer')
        self.timestarted = None
        self.timepaused = None
        self.paused = False

    def start(self):
        """ Starts an internal timer by recording the current time """
        print("Starting timer")
        self.timestarted = datetime.now()

    def pause(self):
        """ Pauses the timer """
        if self.timestarted is None:
            raise ValueError("Timer not started")
        if self.paused:
            raise ValueError("Timer is already paused")
        print('Pausing timer')
        self.timepaused = datetime.now()
        self.paused = True

    def resume(self):
        """ Resumes the timer by adding the pause time to the start time """
        if self.timestarted is None:
            raise ValueError("Timer not started")
        if not self.paused:
            raise ValueError("Timer is not paused")
        print('Resuming timer')
        pausetime = datetime.now() - self.timepaused
        self.timestarted = self.timestarted + pausetime
        self.paused = False

    def get(self):
        """ Returns a timedelta object showing the amount of time
            elapsed since the start time, less any pauses """
        print('Get timer value')
        if self.timestarted is None:
            raise ValueError("Timer not started")
        if self.paused:
            return self.timepaused - self.timestarted
        else:
            return datetime.now() - self.timestarted

if __name__ == "__main__":
    t = MyTimer()
    t.start()
    print('Waiting 2 seconds'); time.sleep(2)
    print(t.get())
    print('Waiting 1 second'); time.sleep(1)
    t.pause()
    print('Waiting 2 seconds [paused]'); time.sleep(2)
    print(t.get())
    print('Waiting 1 second [paused]'); time.sleep(1)
    print(t.get())
    print('Waiting 1 second [paused]'); time.sleep(1)
    t.resume()
    print('Waiting 1 second'); time.sleep(1)
    print(t.get())

Run

python mytimer.py

Output

Initializing timer
Starting timer
Waiting 2 seconds
Get timer value
0:00:02.001523
Waiting 1 second
Pausing timer
Waiting 2 seconds [paused]
Get timer value
0:00:03.004724
Waiting 1 second [paused]
Get timer value
0:00:03.004724
Waiting 1 second [paused]
Resuming timer
Waiting 1 second
Get timer value
0:00:04.008578



回答2:


You can try this code

from tkinter import *

    class TimerTest():
        def __init__(self, root):
            self.root=root

            self.is_running=False  ## timer is or is not running
            self.count=IntVar()
            self.max_seconds=60
            Label(root, textvariable=self.count, font=('DejaVuSansMono', 12, "bold"),
                  bg="lightyellow").grid(row=1, column=0, columnspan=2, sticky="ew")

            Button(root, text="Start", fg="blue", width=15,
                                command=self.startit).grid(row=10, column=0, sticky="nsew")
            Button(root, text="Stop", fg="red", width=15,
                                command=self.stopit).grid(row=10, column=1, sticky="nsew")
            Button(self.root, text="Quit", bg="orange",
                                command=self.root.quit).grid(row=11, column=0,
                                columnspan=2, sticky="nsew")

        def startit(self):
            if not self.is_running:  ## avoid 2 button pushes
                self.is_running=True
                self.increment_counter()

        def increment_counter(self):
            if self.is_running:
                 c=self.count.get() +1
                 self.count.set(c)
                 if c < self.max_seconds:  ## time is not up
                     self.root.after(1000, self.increment_counter)  ## every second
                 else:     ## time is up so exit
                     self.is_running=False
                     Label(root, text="Time Is Up", font=('DejaVuSansMono', 14, "bold"),
                     bg="red").grid(row=5, column=0, columnspan=2, sticky="ew")

        def stopit(self):
            self.is_running = False

    root = Tk()
    TT=TimerTest(root)
    root.mainloop()


来源:https://stackoverflow.com/questions/60026296/how-to-make-a-pausable-timer-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!