ARJhe / tkinter_tutorial

tutorial of tkinter
0 stars 0 forks source link

A rough way to set timer and how to rewrite method that we imported #1

Open ARJhe opened 5 years ago

ARJhe commented 5 years ago
import time as t
from threading import Timer
def timer(self):
    recall = Timer(1.0,self.timer)
    time_elape = t.time() - self.init_time
    label['text']= self.formater(time_elape)
    recall.start()

this way will init threading by every 1 sec, maybe will cause extra loading to CPU. try to rewrite the run function of threading.Timer

origin code:

class Timer(Thread):
    """Call a function after a specified number of seconds:

            t = Timer(30.0, f, args=None, kwargs=None)
            t.start()
            t.cancel()     # stop the timer's action if it's still waiting

    """

    def __init__(self, interval, function, args=None, kwargs=None):
        Thread.__init__(self)
        self.interval = interval
        self.function = function
        self.args = args if args is not None else []
        self.kwargs = kwargs if kwargs is not None else {}
        self.finished = Event()

    def cancel(self):
        """Stop the timer if it hasn't finished yet."""
        self.finished.set()

    def run(self):
        self.finished.wait(self.interval)
        if not self.finished.is_set():
            self.function(*self.args, **self.kwargs)
        self.finished.set()