Python-自定义速度数字时钟

时间:2013-04-19 17:01:01

标签: python user-interface python-2.7 tkinter clock

我正在用python编写程序,我需要一个具有自定义速度的数字时钟。现在,我正在使用一个以正常速度工作并与windows时钟同步的时钟。如何用自定义速度编写数字时钟?

2 个答案:

答案 0 :(得分:0)

custom_time = custom_time0 + (win_time - win_time0)*alpha

其中alpha是自定义因素。

答案 1 :(得分:0)

这是一个有点过度设计的工作示例:

import Tkinter as tk
import functools

class UnconventionalClock(tk.Label):
    '''A label that displays a clock that runs at an unconvetional rate

    usage: x=UnconventionalClock(root, hours, minutes, seconds, interval)
           x.start(); ... ; x.stop()

    'interval' determines how fast one second is, expressed as milliseconds.
    1000 means the clock runs normally; 2000 means it runs at half speed,
    500 means it runs at double speed, etc. 

    '''
    def __init__(self, parent, hours=0, minutes=0, seconds=0, interval=1000):
        tk.Label.__init__(self, parent)
        self._after_id = None
        self.reset(hours, minutes, seconds, interval)

    def start(self):
        self._schedule()

    def stop(self):
        if self._after_id is not None:
            self.after_cancel(self._after_id)
            self._after_id = None

    def reset(self, hours=0, minutes=0, seconds=0, interval=1000):
        self.interval = interval
        self.hours = hours
        self.minutes = minutes
        self.seconds = seconds
        self.configure(text=self._format())

    def _tick(self):
        self.seconds += 1
        if self.seconds >= 60:
            self.seconds = 0
            self.minutes += 1
            if self.minutes >= 60:
                self.minutes = 0
                self.hours += 1
                if self.hours >= 24:
                    self.hours = 0
        self.configure(text=self._format())
        self._schedule()

    def _format(self):
        return "%02d:%02d:%02d" % (self.hours, self.minutes, self.seconds)

    def _schedule(self):
        self._after_id = self.after(self.interval, self._tick)


class Example(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)

        self.clock = UnconventionalClock(self, 23, 59, 40, 500)

        toolbar = tk.Frame(self)
        start = tk.Button(toolbar, text="Start", command=self.clock.start)
        stop = tk.Button(toolbar, text="Stop", command=self.clock.stop)
        start.pack(side="left")
        stop.pack(side="left")

        toolbar.pack(side="top", fill="x")
        self.clock.pack(side="top", fill="x")

root = tk.Tk()
Example(root).pack(side="top", fill="both", expand=True)
root.mainloop()