【问题标题】:Python Kivy - Update Property without using kv-languagePython Kivy - 在不使用 kv 语言的情况下更新属性
【发布时间】:2020-08-03 13:54:48
【问题描述】:

这是我的代码:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty
from kivy.clock import Clock


class MyWidget(Widget):
    score = NumericProperty(0)


class MyWindow(Widget):
    def update(self, dt):
        if self.ids.mywidget.score < 10:
            self.ids.mywidget.score += 1


class MyApp(App):
    def build(self):
        myapp = MyWindow()

        Clock.schedule_interval(myapp.update, .25)
        return myapp


MyApp().run()

kv:

<MyWindow>:
    MyWidget:
        id: mywidget

        Label:
            id: myLabel

            text: '0'
            font_size: 70
            center_x: root.width / 2
            center_y: root.height / 2

我必须在我的 python 文件中进行哪些更改才能使应用程序的行为与我的 kv 文件实际上是这样的相同:

<MyWindow>:
    MyWidget:
        id: mywidget

        Label:
            id: myLabel

            text: str(root.ids.mywidget.score)
            font_size: 70
            center_x: root.width / 2
            center_y: root.height / 2

(我希望标签文本在分数属性更改时更改。)

提前致谢

【问题讨论】:

    标签: python user-interface kivy kivy-language


    【解决方案1】:

    在您的 MyWidget 类中,添加如下方法:

    def on_score(self, *args):
        self.parent.ids.myLabel.text = str(self.score)
    

    每当score属性发生变化时都会调用上述方法,并相应地调整myLabel

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-16
      • 1970-01-01
      • 2021-06-03
      • 2015-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多