Search code examples
pythonkivylabel

kviy: How to change Labels properties remotly from another class through an iterative sentence


I need to change the text in some Labels ive created with a loop sentence. Here is what i've done, but it does not seem to work

from kivy.app import App
from kivy.uix.label import Label
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.relativelayout import RelativeLayout

class MyUI(BoxLayout):
    def __init__(self, **kwargs):
        super(MyUI, self).__init__(**kwargs)
        for i in range(0, 8):
            lbl = Label(text=str(i*10))
            self.add_widget(lbl)

class MainWindow(BoxLayout):

    my_ui = ObjectProperty()
    new_text = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

    def change_text(self):
        for letter in self.new_text:
            if self.my_ui.lbl.text == '30':
                self.my_ui.lbl.text = letter

class MainApp(App):
    pass

if __name__ == '__main__':
    MainApp().run()

And for the kivy file:

MainWindow:

<MainWindow>:
    my_ui: my_ui
    MyUI:
        id: my_ui
    Button:
        text: 'Update Labels'
        on_release: root.change_text()

<MyUI>:

I also don´t know how to target certain label. And I need to do the initialitation of the label box layout through a for loop.


Solution

  • You can do something like that by keeping a list of the Labels created. This version of MyUI does that:

    class MyUI(BoxLayout):
        def __init__(self, **kwargs):
            super(MyUI, self).__init__(**kwargs)
            self.lbls = []  # create list of Labels
            for i in range(0, 8):
                lbl = Label(text=str(i*10))
                self.add_widget(lbl)
                self.lbls.append(lbl)  # add this Label to the list
    

    Then in the change_text() method you can loop through the list of Labels:

    def change_text(self):
        for letter in self.new_text:
            for lbl in self.my_ui.lbls:  # loop through the list of Labels
                if lbl.text == '30':
                    lbl.text = letter