【问题标题】:Dynamically updated Kivy settings entry动态更新的 Kivy 设置条目
【发布时间】:2021-04-30 21:15:57
【问题描述】:

Kivy 有这个很棒的内置功能,可以为您的应用创建设置面板。 它为您提供了一组可以使用的条目类型,例如字符串、布尔值、选项等。 但是所有这些选项都被硬编码在 json 文件中,如果有动态发生,你会怎么做?

如何在 Kivy 中拥有动态变化的设置菜单?

具体来说,我需要一个用于串行连接的设置面板。我的应用程序的用户需要选择他想要连接的现有串行端口。这个列表可以在 python 中获取,但它可以随时更改,那么如何让我的设置菜单与当前的 com 端口可用性保持同步呢?

【问题讨论】:

    标签: python kivy


    【解决方案1】:

    可能有几种方法可以做到这一点。这是其中之一:

    创建一种新类型的设置,它接受一个字符串形式的函数,其中包含每次用户想要查看列表时要调用的函数的完整路径:

    class SettingDynamicOptions(SettingOptions):
        '''Implementation of an option list that creates the items in the possible
        options list by calling an external method, that should be defined in
        the settings class.
        '''
    
        function_string = StringProperty()
        '''The function's name to call each time the list should be updated.
        It should return a list of strings, to be used for the options.
        '''
    
        def _create_popup(self, instance):
            # Update the options
            mod_name, func_name = self.function_string.rsplit('.',1)
            mod = importlib.import_module(mod_name)
            func = getattr(mod, func_name)
            self.options = func()
        
            # Call the parent __init__
            super(SettingDynamicOptions, self)._create_popup(instance)
    

    它是 SettingOptions 的子类,允许用户从下拉列表中进行选择。每次用户按下设置查看可能的选项时,都会调用_create_popup 方法。新的重写方法动态导入函数并调用它来更新类的选项属性(反映在下拉列表中)。

    现在可以在 json 中创建这样的设置项:

        {
            "type": "dynamic_options",
            "title": "options that are always up to date",
            "desc": "some desc.",
            "section": "comm",
            "key": "my_dynamic_options",
            "function_string": "my_module.my_sub_module.my_function"
        },
    

    还需要通过继承 Kivy 的设置类来注册新的设置类型:

    class MySettings(SettingsWithSidebar):
        '''Customized settings panel.
        '''
        def __init__(self, *args, **kargs):
            super(MySettings, self).__init__(*args, **kargs)
            self.register_type('dynamic_options', SettingDynamicOptions)
    

    并将其用于您的应用:

        def build(self):
            '''Build the screen.
            '''
            self.settings_cls = MySettings
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-26
      • 1970-01-01
      • 2017-10-08
      • 1970-01-01
      • 2021-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多