Kivy - 如何通过Clock将变量传递给KV语言

0 投票
1 回答
1553 浏览
提问于 2025-04-18 16:49

我正在尝试使用Kivy框架写一个简单的倒计时器应用。所有的变量我都已经准备好了,现在只需要把它们传递给KV语言来显示。但是,我在传递这些值时遇到了问题。

import datetime
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.clock import Clock
from kivy.properties import StringProperty, NumericProperty

class Counter_Timer(BoxLayout):
    days = StringProperty()
    hours = StringProperty()
    minutes = StringProperty()
    seconds = StringProperty()

    def update(self, dt):
        delta = datetime.datetime(2014, 9, 13, 3, 5) - datetime.datetime.now()
        self.days = str(delta.days)
        hour_string = str(delta).split(', ')[1]
        self.hours = hour_string.split(':')[0]
        self.minutes = hour_string.split(':')[1]
        self.seconds = hour_string.split(':')[2].split('.')[0]

class Counter(App):
    def build(self):
        counter = Counter_Timer()
        Clock.schedule_interval(counter.update, 1.0)
        return Counter_Timer()


if __name__=='__main__':
    Counter().run()

KV:

<Counter_Timer>:
    orientation: 'vertical'
    Label: 
        text: 'Days '
        font_size: '30dp'
    Label:
        font_size: '30dp'
        # text value with days left.
        text: root.days

代码没有报错,但剩余的天数没有显示出来。

我觉得我用root.property来访问变量的方式是对的,但使用Clock会不会有什么影响呢?我哪里出错了?

1 个回答

1
def build(self):
    counter = Counter_Timer()
    Clock.schedule_interval(counter.update, 1.0)
    return Counter_Timer()

你安排了一个更新你的计数器实例,这个过程运行得很好,但之后你返回了一个新的、不同的 Counter_Timer。因为你从来没有改变它的属性,所以它的文本内容就不会更新。

其实你只需要改成 return counter 就可以了。

撰写回答