Search code examples
pythontextlabelkivykivy-language

How to set the text of a custom widget from the parent in KV lang?


Suppose you have a custom layout which contains labels that should not be set locally, for example

<CustomWidget>:
    Label:
        id: l1
    Label:
        id: l2

In this case, CustomLabels is a layout such as GridLayout. When this custom widget is put into use, you'll need to set the text, and it is ugly if this is done within Python. Can it be done from within kivy? For instance,

SomeLayout:
    ...
    CustomWidget:
        l1.text: "hello, "
        l2.text: "world!"
    ...

Of course, this raises a syntax error on the first assignment of l1.text. Any ideas?


Solution

  • If you define your CustomWidget with some StringProperties, like this:

    class CustomWidget(SomeOtherLayout):
        l1_text = StringProperty()
        l2_text = StringProperty()
    

    Then change your kv slightly:

    <CustomWidget>:
        Label:
            text: root.l1_text
        Label:
            text: root.l2_text
    

    Then you can use the CustomWidget as:

    SomeLayout:
        CustomWidget:
            l1_text: "hello, "
            l2_text: "world!"