Reputation: 601
I am learning how to implement the Kivy settings panel. It'd be perfect for several use cases, but I cannot figure out how to get the values of the settings to show in my app immediately after the build.
I borrowed this example code from PalimPalims answer here. It works great when you change the settings, but prior to changing the value in the settings panel, the Label widget has no text. I tried adding it in the kv language section text text: App.get_running_app().config.get('Label','content')
after import App into the build section.
I also tried assigning the widgets value in the Apps build function but kept getting an error 'MyApp has no ids'. I have to believe this is doable and I'm just reading over the method in the docs.
from kivy.app import App
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.config import Config
class Labelwithconfig(Label):
def check_label(self):
self.text = App.get_running_app().config.get('Label','content')
kv_str = Builder.load_string("""
BoxLayout:
orientation: 'vertical'
Labelwithconfig:
id: labelconf
Button:
text: 'open settings'
on_press: app.open_settings()
""")
class MyApp(App):
def build_config(self, config):
config.setdefaults('Label', {'Content': "Default label text"})
def build_settings(self, settings):
settings.add_json_panel("StackOverflow Test Settings", self.config, data="""
[
{"type": "options",
"title": "Label text System",
"section": "Label",
"key": "Content",
"options": ["Default label text", "Other Label text"]
}
]"""
)
def on_config_change(self, config, section, key, value):
self.root.ids.labelconf.check_label()
def build(self):
return kv_str
if __name__ == '__main__':
MyApp().run()
Upvotes: 3
Views: 1060
Reputation: 1226
text: App.get_running_app().config.get('Label','content')
won't display your text when your app starts up because the content of your kv
file is loaded before your App
class has fully loaded. To do what you want, overwrite the on_start
method of the App
class (this is a super handy trick that is hard to discover sometimes for new users).
def on_start(self):
self.root.ids.labelconf.text = self.config.get('Label','content')
From the kivy docs:
on_start()
Event handler for the on_start event which is fired after initialization (after build() has been called) but before the application has started running.
Basically, you are able to access your app's variables like self.whatever
once the build()
function has finished. on_start()
is automatically called when build()
finishes.
Upvotes: 4