使用Clock.schedule_interval每秒更新一个显示的变量

问题描述 投票:2回答:1

我有schedule_interval调用一个从Web获取天气数据然后将其解析为dict的函数。我有我的kv文件读取dict并在floatlayout中显示值。我知道正在调用该函数,因为我也将它打印到控制台,但它没有在floatlayout窗口中更新。我认为这些值会自动从我读过的内容中更新。

GUI.py
class weather(FloatLayout):
    def w(self):
        a = parse()
        print(a)
        return a

class weatherApp(App):
    def build(self):
        d = weather()
        Clock.schedule_interval(d.w, 1)
        return d

weather.kv
<Layout>:
     DragLabel:
        font_size: 600
        size_hint: 0.1, 0.1
        pos: 415,455
        text: str(root.w()['temp0'])

这只是其中一个标签。我对Kivy很新,所以如果这对你经验丰富的kivy看起来很残忍,我道歉。

def(self)的print(a)部分:每秒工作一次,但窗口不显示新变量。

test.py

from kivy.app import App
from kivy.clock import Clock
from kivy.uix.floatlayout import FloatLayout

a = {}
a['num'] = 0

class test(FloatLayout):
    def w(self):
        a['num'] += 1
        print(a['num'])
        return a

class testApp(App):
    def build(self):
        d = test()
        Clock.schedule_interval(test.w, 1)
        return d

if __name__ == '__main__':
    p = testApp()
    p.run()


test.kv

#:kivy 1.10.1

<Layout>:
    Label:
        font_size: 200
        size_hint: 0.1, 0.1
        pos: 415,455
        text: str(root.w()['num'])

python kivy
1个回答
0
投票

你似乎有几个误解:

  • 如果你在python中调用一个函数,它并不意味着将调用.kv。因此,如果使用Clock.schedule_interval()调用w方法,则并不意味着计算的值会更新Label文本的值。
  • 使用Clock.schedule_interval调用函数时,必须使用对象而不是类。在你的情况下,测试是类,而d是对象。

使用Clock.schedule_interval调用函数时,必须使用对象而不是类。在你的情况下,测试是类,而d是对象。

*的.py

from kivy.app import App
from kivy.clock import Clock
from kivy.uix.floatlayout import FloatLayout
from kivy.properties import DictProperty


class test(FloatLayout):
    a = DictProperty({"num": 0})

    def w(self, dt):
        self.a["num"] += 1
        print(self.a["num"])


class testApp(App):
    def build(self):
        d = test()
        Clock.schedule_interval(d.w, 1)
        return d


if __name__ == "__main__":
    p = testApp()
    p.run()

#:kivy 1.10.1

<Layout>:
    Label:
        font_size: 200
        size_hint: 0.1, 0.1
        pos: 415,455
        text: str(root.a["num"])
© www.soinside.com 2019 - 2024. All rights reserved.