使用更改的配置更新Kivy设置面板值

2024-10-03 17:27:34 发布

您现在位置:Python中文网/ 问答频道 /正文

问题:

我正在构建一个应用程序,并使用kivy settingspanel更改设置。某些设置存储在ConfigParserProperties中,也可以在设置面板之外进行更改。当我重新打开“设置”面板时,“设置”面板中的值仍然是旧值。
如何使用最新值(在ConfigParserProperties中)更新设置面板?

我所尝试的:

  • 我找到了这个Dynamically updated Kivy settings entry,但这里只创建了一个小部件进行更新(一个列表弹出窗口)。我正在寻找一种方法来更新不同类型的多个设置项

  • 我让设置面板更新的唯一方法是销毁它,并在每次打开时重新创建它(代码见下文)。如果面板包含多个页面,这是一个(明显的)缓慢的过程(在本例中,为了保持简单,情况并非如此)

例如:

此示例为变量测试生成随机值,该值是“设置”面板中的唯一项(通过单击按钮或按f1键打开)。 正如您所看到的,该值不会从起始值更改

from kivy.app import App
from kivy.properties import ConfigParserProperty
from random import randint
from kivy.clock import Clock
from kivy.uix.button import Button
import json


class MyApp(App):
    test = ConfigParserProperty(0, 'testing', 'test_par', 'app_config', val_type=int)
    use_kivy_settings = False   # disable kivy settings in options

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        Clock.schedule_interval(self.new_number, 1)

    def build(self):        
        self.config.read("test.ini")
        self.config.name = "app_config"
        _app = super().build()
        _app.add_widget(Button(text='open settings', 
                               size=_app.size, 
                               pos=_app.pos, 
                               on_release=self.open_settings))
        return _app

    def build_settings(self, settings):
        _setts = json.dumps([
        {
            "type": "title",
            "title": "Test Settings"
        },
        {
            "type": "numeric",
            "title": "Test Var",
            "desc": "Randomly changing test var, wish it would change here too",
            "section": "testing",
            "key": "test_par"
        }])
        settings.add_json_panel('Test Panel', self.config, data=_setts)
        self.settings = settings

    def new_number(self, *args, **kwargs):
        # generate random new values for test
        self.test = randint(0, 0xff)
        print(self.test)

if __name__ == "__main__":
    app = MyApp()
    app.run()

我的尝试:
添加此代码将在每次打开面板时更改该值。但也会在每次打开面板时销毁和重新创建面板。使用多个面板项目时速度较慢

    def open_settings(self, *args):
        self.destroy_settings()  # clear settings
        return super().open_settings(*args)

如果有人知道如何通过ConfigParserProperties中的更改来更改/更新特定的面板项,我们将不胜感激


Tags: fromtestimportselfconfigjsonapp面板