Kivy: Access configuration values from any widget

2024/10/5 13:29:40

I'm using kivy to create a small App for computer aided learning.

At the moment I have some problems with accessing config values. I get the value with

self.language = self.config.get('basicsettings', 'language')

in the main App-Class. That works fine, however, I don't know how to access these value inside another widget - in this case the AudioButton.

I'm using a ScreenManager, which contains a Screen. Inside is a BoxLayout, which contains a GridLayout and this holds several AudioButtons.

Now, in this AudioButton I want to know the current value of self.language defined in the mainApp.

In .kv files I can do something like

`text: app.language`

to get it, but how to do it directly in Python?

If I use a dummy label in kv to get the value, it works, but when I change the setting, I need to restart the App, because I don't know what I need to add to on_config_change() to update the value during runtime.

Here's a very simplified version of my App with all interesting parts, I hope.

class AudioButton(Button):filename = StringProperty(None)sound = ObjectProperty(None, allownone=True)def on_press(self):if self.ids.playsound.text == '1':self.sound.play()else:print('NoSound')class MainScreen(Screen):passclass Pictures1(GridLayout):def __init__(self, **kwargs):super(Pictures1, self).__init__(**kwargs)self.cols = 2btn = AudioButton()self.add_widget(btn)btn = AudioButton()self.add_widget(btn)class Lesson1(Screen):passclass ScreenManagement(ScreenManager):passclass LunahutsoApp(App):def build(self):self.settings_cls = SettingsWithSidebarself.use_kivy_settings = Falseself.language = self.config.get('basicsettings', 'language')self.playsound = self.config.get('basicsettings', 'playsound')return ScreenManagement()def build_config(self, config):config.setdefaults('basicsettings', {'language': 'austrian','playsound': 1})def build_settings(self, settings):settings.add_json_panel('Lunahutso',self.config,data=settings_json)def on_config_change(self, config, section,key, value):if key == 'language':self.language = valueif key == 'playsound':self.playsound = valueif __name__ == "__main__":LunahutsoApp().run()

And the .kv file:

<ScreenManagement>:MainScreen:Lesson1:<AudioButton>:Label:id: languagetext: app.languagecolor: 0, 0, 0, 0Label:id: playsoundtext: app.playsoundcolor: 0, 0, 0, 0<MainScreen>:name: "main"BoxLayout:orientation: 'vertical'Button:on_release: app.root.current = "lesson1"text: "Lesson"font_size: 50Button:on_release: app.open_settings()text: "Settings"font_size: 50Button:on_release: sys.exit()text: "Quit"font_size: 50<Lesson1>:name: "lesson1"id: lesson1BoxLayout:orientation: 'vertical'Pictures1:size_hint_y: 0.5BoxLayout:size_hint_y: 0.15Label:text: ""
Answer

You can use the following method of the app class get_running_app(), see here https://kivy.org/docs/api-kivy.app.html#kivy.app.App.get_running_app

This way you can reference the config from another class through the app class.

I wrote a quick example below. I am using self.text = App.get_running_app().config.get('Label','content') to access sth in the config.

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 Configclass 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: labelconfButton: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_strif __name__ == '__main__':MyApp().run()
https://en.xdnf.cn/q/70486.html

Related Q&A

Multiprocessing with threading?

when I trying to make my script multi-threading, Ive found out multiprocessing,I wonder if there is a way to make multiprocessing work with threading?cpu 1 -> 3 threads(worker A,B,C) cpu 2 -> 3 …

Pandas Groupby Unique Multiple Columns

I have a dataframe.import pandas as pd df = pd.DataFrame( {number: [0,0,0,1,1,2,2,2,2], id1: [100,100,100,300,400,700,700,800,700], id2: [100,100,200,500,600,700,800,900,1000]})id1 id2 nu…

OpenCV Error: Assertion failed when using COLOR_BGR2GRAY function

Im having a weird issue with opencv. I have no issues when working in a jupyter notebook but do when trying to run this Sublime.The error is: OpenCV Error: Assertion failed (depth == CV_8U || depth == …

matplotlib 1.3.1 has requirement numpy=1.5, but youll have numpy 1.8.0rc1 which is incompatible

Im executing bellow command in Mac (High Sierra) as a part of getting started with pyAudioAnalysis.pip install numpy matplotlib scipy sklearn hmmlearn simplejson eyed3 pydub Im getting following error…

VS Code Debugger Immediately Exits

I use VS Code for a python project but recently whenever I launch the debugger it immediately exits. The debug UI will pop up for half a second then disappear. I cant hit a breakpoint no matter where i…

Sudoku Checker in Python

I am trying to create a sudoku checker in python:ill_formed = [[5,3,4,6,7,8,9,1,2],[6,7,2,1,9,5,3,4,8],[1,9,8,3,4,2,5,6,7],[8,5,9,7,6,1,4,2,3],[4,2,6,8,5,3,7,9], # <---[7,1,3,9,2,4,8,5,6],[9,6,1,5,…

Subclassing numpy scalar types

Im trying to subclass numpy.complex64 in order to make use of the way numpy stores the data, (contiguous, alternating real and imaginary part) but use my own __add__, __sub__, ... routines.My problem i…

Python file IO w vs wb [duplicate]

This question already has answers here:What does wb mean in this code, using Python?(5 answers)Closed 10 years ago.Wondering what the real difference is when writing files from Python. From what I can…

How to extract hour, minute and second from Series filled with datetime.time values

Data:0 09:30:38 1 13:40:27 2 18:05:24 3 04:58:08 4 09:00:09Essentially what Id like to do is split this into three columns [hour, minute, second]Ive tried the following code but none see…

Getting an error attachment_filename does not exist in my docker environment

Due to some reasons this particular code is not working in docker but it works fine in development environment. I am getting error "TypeError: send_file() got an unexpected keyword argument attach…