How to update label text in .kv using properties in .py?

I want to update values in my class MainHero using button in .kv and based on attribute nick in my class I need to update label in .kv. I need to handle this automatically, because many other attributes will be generated automatically so labels need to be updated. Here is part of my code:

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import StringProperty
from kivy.lang import Builder


class MainHero():
     def __init__(self):
          self.nick = "Player"

class FightScreen(Screen):
    def __init__(self, **kwargs):
        super(MainScreen, self).__init__(**kwargs)
        self.af_init = Clock.create_trigger(self._init)
        self.af_init()

    def _init(self, dt):
         self.app = App.get_running_app()
    
    def rename(self):
        self.app.main_hero.nick = "Renamed"


class ScreenManagement(ScreenManager):
    pass



class Design(App):
    def __init__(self, **kwargs):
        super(Design, self).__init__(**kwargs)
        self.main_hero = MainHero() # Tried main_hero = MainHero() too
        self.val = StringProperty(self.main_hero.nick)  # string

    # Construct app
    def build(self):
        # design constructor
        kv = Builder.load_file('AppDesign.kv')
        return kv

if __name__ == "__main__":
    Design().run()
# Using kv 2.0
ScreenManagement:
    id: screen_manager
    FightScreen:
        name: 'FightScreen'
        manager: screen_manager
        id: fight_screen

<FightScreen>

FloatLayout:
     BasicBackground
     Label:
          text: app.val
          size_hint: .2, .2
          pos_hint: {'center_x': .5, 'center_y': .35}
     Button:
          size_hint: .2, .2
          pos_hint: {'center_x': .5, 'center_y': .5}
          on_press:
               root.rename()
          

It is probably possible through properties/EventDispetcher. Reference app.val in many cases I tried is something like <StringProperty name=>. I tried using (maybe wrong)

class Aaa(EventDispetcher); apply_property(**kwargs)



Read more here: https://stackoverflow.com/questions/67391902/how-to-update-label-text-in-kv-using-properties-in-py

Content Attribution

This content was originally published by Master at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: