Kivy:从任何小部件访问配置值 [英] Kivy: Access configuration values from any widget

查看:110
本文介绍了Kivy:从任何小部件访问配置值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用kivy创建一个用于计算机辅助学习的小型应用程序.

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')

.效果很好,但是,我不知道如何在另一个小部件(在本例中为AudioButton)中访问这些值.

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.

我正在使用包含屏幕的ScreenManager.内部是一个BoxLayout,其中包含一个GridLayout,其中包含几个AudioButton.

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

现在,在此AudioButton中,我想知道mainApp中定义的self.language的当前值.

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

在.kv文件中,我可以做类似的事情

In .kv files I can do something like

`text: app.language`

要获取它,但是如何直接在Python中实现呢?

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

如果我在kv中使用虚拟标签来获取值,它可以工作,但是当我更改设置时,我需要重新启动应用程序,因为我不知道需要添加到on_config_change()中进行更新运行时的值.

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.

我希望这是我的App的非常简化的版本,其中包含所有有趣的部分.

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):
    pass


class Pictures1(GridLayout):
    def __init__(self, **kwargs):
        super(Pictures1, self).__init__(**kwargs)
        self.cols = 2
        btn = AudioButton()
        self.add_widget(btn)
        btn = AudioButton()
        self.add_widget(btn)


class Lesson1(Screen):
    pass


class ScreenManagement(ScreenManager):
    pass


class LunahutsoApp(App):
    def build(self):
        self.settings_cls = SettingsWithSidebar
        self.use_kivy_settings = False
        self.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 = value
        if key == 'playsound':
            self.playsound = value


if __name__ == "__main__":
    LunahutsoApp().run()

.kv文件:

<ScreenManagement>:
    MainScreen:
    Lesson1:

<AudioButton>:
    Label:
        id: language
        text: app.language
        color: 0, 0, 0, 0
    Label:
        id: playsound
        text: app.playsound
        color: 0, 0, 0, 0

<MainScreen>:
    name: "main"
    BoxLayout:
        orientation: 'vertical'
        Button:
            on_release: app.root.current = "lesson1"
            text: "Lesson"
            font_size: 50
        Button:
            on_release: app.open_settings()
            text: "Settings"
            font_size: 50
        Button:
            on_release: sys.exit()
            text: "Quit"
            font_size: 50

<Lesson1>:
    name: "lesson1"
    id: lesson1
    BoxLayout:
        orientation: 'vertical'
        Pictures1:
            size_hint_y: 0.5
        BoxLayout:
            size_hint_y: 0.15
            Label:
                text: ""

推荐答案

您可以使用应用类get_running_app()的以下方法,请参见此处

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.

我在下面写了一个简单的例子.我正在使用self.text = App.get_running_app().config.get('Label','content')访问配置中的sth.

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 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()

这篇关于Kivy:从任何小部件访问配置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆