【问题标题】:Kivy: Self-updating label textKivy:自更新标签文本
【发布时间】:2023-03-09 05:56:01
【问题描述】:

假设我有 3 个类:一个发生事情的“工作类”、一个标签类和一个包含它们的类。 例如,标签类可以是一个状态栏,显示正在工作的某事的状态。我希望我能找到一种方法让标签自动更新要显示的值,因为这个值是在后者内部被更改的工作类的值。

这里有一个示例代码

Builder.load_string('''
<CustomLabel>
    text: 'Value is {}'.format(root.value)

<WorkingClass>:
    orientation: 'vertical'

    Button:
        text: 'Update'
        on_release: root.update()

<MainLayout>
    orientation: 'vertical'

''')

class CustomLabel(Label):
    value = NumericProperty()

class WorkingClass(BoxLayout):

    def __init__(self, *args, **kwargs):

        super(WorkingClass, self).__init__(*args, **kwargs)

        self.a = 5

    def update(self):
        self.a += 1
        print(self.a)

class MainLayout(BoxLayout):

    def __init__(self, *args, **kwargs):

        super(MainLayout, self).__init__(*args, **kwargs)

        self.workingClass = WorkingClass()
        self.customLabel = CustomLabel(value=self.workingClass.a)

        self.add_widget(self.customLabel)
        self.add_widget(self.workingClass)





class MyApp(App):
    def build(self):
        return MainLayout()

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

有没有办法用属性或其他方法来做到这一点?因为我不想每次更改值时都需要手动更新(不知何故)标签。无论如何要做到这一点?

【问题讨论】:

    标签: python kivy


    【解决方案1】:

    您正在更新WorkingClass 上的属性,但这不会更新CustomLabel 上的值,因为您执行的是直接分配而不是bind 分配它。但是是的,您可以使用Propertys 让一切自动运行。

    WorkingClass:

    class WorkingClass(BoxLayout):
        a = NumericProperty()
    
        def __init__(self, **kwargs): ...
    

    这使a 变成了您可以绑定的Property

    然后在MainLayout的构造函数中:

    self.workingClass = WorkingClass()
    self.customLabel = CustomLabel(value=self.workingClass.a)
    self.workingClass.bind(a=self.customLabel.setter('value'))
    

    最后一行说:“当self.workingClass上的属性a的值发生变化时,将self.customLabelvalue属性设置为相同的值”

    或者,您可以将Property 添加到上面的WorkingClass,然后去掉MainLayout 的构造函数并改用kv:

    <MainLayout>:
        orientation: 'vertical'
    
        WorkingClass:
            id: working_class
    
        CustomLabel:
            value: working_class.a  # assigning one property to another in kv automatically binds
    

    【讨论】:

    • 非常感谢!我不知道二传手!我只是注意到总是你回答我的问题,非常感谢你!
    猜你喜欢
    • 1970-01-01
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多