Kivy简单倒计时分秒计时器

时间:2017-01-30 13:32:22

标签: python datetime time kivy

所以我想建立一个基本只是倒计时一分钟和几秒钟的kivy程序。

这就是我走了多远:

from kivy.app import App
from kivy.uix.label import Label
from kivy.clock import Clock

from datetime import datetime, date, time


class IncrediblyCrudeClock(Label):
    a = time(0, 1, 1)

    def update(self, *args):
        self.text = str(self.a)
        print(str(self.a))

        self.a = datetime.combine(date.today(), self.a) - datetime.combine(date.today(), time(0,0,1))

class TimeApp(App):
    def build(self):
        crudeclock = IncrediblyCrudeClock()
        Clock.schedule_interval(crudeclock.update, 1)
        return crudeclock

if __name__ == "__main__":
    TimeApp().run()

问题在于,当我尝试从新时间中扣除旧时间时,我显示的时间少了1秒,我收到以下错误:

self.a = datetime.combine(date.today(), self.a) datetime.combine(date.today(), time(0,0,1))
 TypeError: combine() argument 2 must be datetime.time, not datetime.timedelta

这让我觉得,在第一次推动之后,a现在不是"时间"对象,但是" timedelta"不幸的是,不能扣除。

任何帮助都会很棒!

1 个答案:

答案 0 :(得分:1)

如果您只是需要倒计时,有一种更简单的方法。你可以使用kivy的Animation类,@ {3}}上的@inclement很好地描述了这个类。 所以这里是代码(main.py和time.kv):

<强> main.py

from kivy.app import App
from kivy.uix.label import Label
from kivy.animation import Animation
from kivy.properties import StringProperty, NumericProperty


class IncrediblyCrudeClock(Label):
    a = NumericProperty(5)  # seconds

    def start(self):
        Animation.cancel_all(self)  # stop any current animations
        self.anim = Animation(a=0, duration=self.a)
        def finish_callback(animation, incr_crude_clock):
            incr_crude_clock.text = "FINISHED"
        self.anim.bind(on_complete=finish_callback)
        self.anim.start(self)

class TimeApp(App):
    def build(self):
        crudeclock = IncrediblyCrudeClock()
        crudeclock.start()
        return crudeclock

if __name__ == "__main__":
    TimeApp().run()

<强> time.kv

<IncrediblyCrudeClock>
    text: str(round(self.a, 1))

享受! :)

更新

OP请求没有kv文件的解决方案 - 所以这里有一个:

from kivy.app import App
from kivy.uix.label import Label
from kivy.animation import Animation
from kivy.properties import StringProperty, NumericProperty


class IncrediblyCrudeClock(Label):
    a = NumericProperty(5)  # seconds

    def start(self):
        Animation.cancel_all(self)  # stop any current animations
        self.anim = Animation(a=0, duration=self.a)
        def finish_callback(animation, incr_crude_clock):
            incr_crude_clock.text = "FINISHED"
        self.anim.bind(on_complete=finish_callback)
        self.anim.start(self)

    def on_a(self, instance, value):
        self.text = str(round(value, 1))

class TimeApp(App):
    def build(self):
        crudeclock = IncrediblyCrudeClock()
        crudeclock.start()
        return crudeclock

if __name__ == "__main__":
    TimeApp().run()