【问题标题】:Updating a displayed variable every second with Clock.schedule_interval使用 Clock.schedule_interval 每秒更新一个显示的变量
【发布时间】:2019-04-27 00:34:50
【问题描述】:

我有 schedule_interval 调用一个从 web 获取天气数据然后将其解析为 dict 的函数。我有我的 kv 文件读取该字典并在浮动布局中显示值。我知道该函数正在被调用,因为我也将它打印到控制台,但它没有在 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 w(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'])

【问题讨论】:

  • 谢谢,我只是添加了一个test.py和test.kv的形式

标签: python kivy


【解决方案1】:

看来你有几个误解:

  • 如果你在 python 中调用一个函数,它并不意味着 .kv 将被调用。因此,如果您使用 Clock.schedule_interval() 调用 w 方法,并不意味着计算的值会更新 Label 文本的值。

  • 当您使用 Clock.schedule_interval 调用函数时,您必须使用对象而不是类。在您的情况下, test 是类,而 d 是对象。

当您使用 Clock.schedule_interval 调用函数时,您必须使用对象而不是类。在您的情况下, test 是类,而 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()

*.kv

#:kivy 1.10.1

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

【讨论】:

  • 首先,谢谢。我能够将此解决方案应用于我的主程序并且它有效。如此草率地调用我的 dict 对象是问题所在?
  • @stephenlendl Kivy 和许多其他 GUI 存在于事件循环中,因此它们使用某些元素(在 kivy 属性的情况下)来通知更改。在您的情况下,使用 dict 不会通知事件循环更改,而是使用 DictProperty 。如果我的回答对您有帮助,请不要忘记将其标记为正确,如果您不知道该怎么做,请查看tour
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-28
  • 2021-09-24
  • 1970-01-01
  • 1970-01-01
  • 2018-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多