Kivy: self-updating label text

Say I have 3 classes: the “woking class”, where the material happens, the label class, and the class to contain them. For example, a label class can be a status bar that displays the status of something that happens in a working class. I wish I could find a way to make the label a self-updated value to show, since this value is the value of a working class that changes inside the latter.

Here I have a sample code

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()

Is there a way to do this with properties or something else? Becouse I don’t want to manually update the (sommehow) label every time I change the value. Anyway to achieve this?

0
source share
1 answer

WorkingClass, CustomLabel, bind. , Property, .

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'))

: " a self.workingClass , value self.customLabel "

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
+2

Source: https://habr.com/ru/post/1671129/


All Articles