0

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

4

2 回答 2

1

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

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()
于 2013-04-20T13:02:51.120 回答
0
custom_time = custom_time0 + (win_time - win_time0)*alpha

alpha自定义因素在哪里。

于 2013-04-19T17:12:27.670 回答