2015-10-15 78 views
0

Kivy具有創建適用於您的應用的設置面板的超棒內置功能。 它爲您提供了一組您可以使用的字符串,布爾,選項等。 但是,所有這些選項都是在json文件中進行硬編碼的,如果發生某些動態的事情,您會怎麼做?動態更新的Kivy設置條目

如何在Kivy中設置一個動態變化的設置菜單?

具體來說,我需要一個串行連接的設置面板。我的應用程序的用戶需要選擇他想要連接的現有串行端口。這個列表可以在python中獲得,但它可以隨時更改,那麼如何使我的設置菜單保持與當前的com端口一致?

回答

2

有可能有幾種方法來做到這一點。這裏是其中的一個:

創建一個新的類型設置的,它接受一個函數作爲字符串,將包含你希望每個用戶想要看列表時,調用該功能的完整路徑:

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方法。新的overriden方法動態導入該函數並調用它來更新類的選項屬性(這反映在下拉列表中)。

現在,可以在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