Search code examples
pythonkivy

Label Text is Not Changing Kivy Python


I am trying to change label text when I press a button, but it does not change. I have this code:

Controler:

class Controller(BoxLayout):
    random_string = StringProperty()
    random_string="hola"
    def do_action(self):
        random_string="h22l"
        print(random_string)
    def do_action2(self):
        random_string="hl2332323"
        print(str(random_string))

My .mk:

<Controller>:
    label: lvId

BoxLayout:
    orientation: 'vertical'

    Button:
        text: 'Click Me'
        on_press: root.do_action()
    
    Button:
        text: 'Click Me'
        on_press: root.do_action2()
    
    Label:
        id: lvId
        text: root.random_string
        text_size: root.width, None
        size: self.texture_size

Solution

  • You have to access the variable through self, if you do not, you will be creating a new local variable other than the one you want to access.

    class Controller(BoxLayout):
        random_string = StringProperty("hola")
        def do_action(self):
            self.random_string="h22l"
            print(self.random_string)
        def do_action2(self):
            self.random_string="hl2332323"
            print(self.random_string)