清理/验证Kivy设置用户输入

时间:2018-03-27 13:59:46

标签: python validation kivy settings

如果你使用Kivy提供的ConfigParser / Settings并添加你自己在json中定义的设置,那么你只有两种类型的安全设置:“type”:“options”和“type”:“bool”。原因是,其他类型将为用户提供textinput小部件,他们可以在其中输入他们喜欢的任何内容。例如。 import os; os.system("rm -r ~")。但是,给定的设置可能有许多不同的值(实际上我正在处理一个设置,它有许多不同的可能值)。所以我不能只使用两种安全类型,因为它会炸掉屏幕。

所以我深入研究了github上的ConfigParser和Settings类,我找到了config.add_callback。您可以使用build方法访问配置对象,因此我使用了该方法并添加了self.config.add_callback(self.validate_settings_input)。您添加的回调函数将获取on_config_change获取的所有参数,第一个(config除外)。所以我将验证码添加到self.validate_settings_input。如果用户输入无效,我想覆盖它,因此我添加了self.config.set('MySection', 'MyKey', override_value)config.write()。但这不起作用,或者至少它不起作用,因为我期望它起作用:

对于以下描述,请注意存在一个class属性,该属性设置为设置值(接线位于on_config_change)。如果单击该设置,将弹出带有textinput的弹出窗口。如果输入有效值并按OK提交,则更改设置(在配置文件中,在Settings-GUI和programm / class中)。但是,如果键入无效值,则设置也会更改(在配置文件中,在Settings-GUI中,但不在programm / class中)。如果您随后关闭应用程序并再次启动它,则该设置将更改为有效值,如self.validate_settings_input中所定义。

因此,我的验证正确完成的唯一情况是on_start()。虽然每次调用ConfigParser时都应调用使用add_callback添加到config.set()的回调。并且在不知道的情况下我假设即使用户通过GUI更改设置也会调用config.set()。如果没有,这一切有什么意义呢?

谷歌“Kivy输入验证”只产生一个stackoverflow问题,没有答案。此问题也与普通的textinput小部件有关。但是,我关注的textinput小部件是某些Settings类的内部对象。

您对如何清理/验证用户输入设置有什么建议吗?

示例代码

###############################################################################
# Version
###############################################################################

__version__ = '0.1'



###############################################################################
# Imports
###############################################################################


# Python build-in Modules
from functools import partial   # schedule callback functions that take arguments different from 'dt'

# Kivy
from kivy.lang.builder import Builder
from kivy.app import App
from kivy.core.window import Window
from kivy.utils import platform
from kivy.uix.screenmanager import Screen
from kivy.properties import ObjectProperty, NumericProperty, StringProperty

from kivy.uix.settings import SettingsWithTabbedPanel
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView

from kivy.clock import Clock
from kivy.uix.label import Label
from kivy.logger import Logger




###############################################################################
# Constants
###############################################################################

BACKGROUND_COLOR = [0,0,0,0]
TEXT_COLOR = [1,1,1,1]


JSON_MATH = '''
[
    {
        "type": "string",
        "title": "Operator (free choice)",
        "desc": "Choose the operator. + (addition). - (subtraction). * (multiplication). : (division). % (modulo). You can also choose any combination of those operations to create your own mix.",
        "section": "Math",
        "key": "operator"
    },
    {
        "type": "options",
        "title": "Operator (options)",
        "desc": "Choose the operator. + (addition). - (subtraction). * (multiplication). : (division). % (modulo). You can also choose from three mixes.",
        "options": ["+", "-", "*", ":", "%", "+-", "*:", "+-*:"],
        "section": "Math",
        "key": "operator_"
    }
]
'''

kv_string = """
<MySettingsRoot>:
    orientation: 'vertical'

    Label:
        text: '[b] My Settings App [/b]'
        markup: True

    Button:
        text: 'Settings'
        on_release: app.open_settings()

    Button:
        text: 'Quit'   
        on_release: app.stop()
"""



###############################################################################
# Widgets
###############################################################################




###############################################################################
# Root Widget
###############################################################################

class MySettingsRoot(BoxLayout):
    """ See kv string
    """
    def __init__(self, *args, **kwargs):
        super(MySettingsRoot, self).__init__(*args, **kwargs)


    def changeScreen(self, next_screen):
        pass    

    def onBackBtnPress(self):
        pass



###############################################################################
# App Object
###############################################################################

class MySettingsApp(App):
    """ App object
    """
    def __init__(self, *args, **kwargs):
        super(MySettingsApp, self).__init__(*args, **kwargs)
        #self.use_kivy_settings = False
        self.settings_cls = SettingsWithTabbedPanel         

    def build(self):
        Builder.load_string(kv_string)
        self.config.add_callback(self.config_input_validation)
        return MySettingsRoot()

    def build_config(self, config):
        config.setdefaults('Math', {'operator': '+-:%', 'operator_': '*'})

    def build_settings(self, settings):
        settings.add_json_panel('Math', self.config, data=JSON_MATH)

    def config_input_validation(self, section, key, value, *args):
        """ Callback function, which is bound to the same event as on_config_change.
            It is supposed to validate the value that a user sets some setting to.
            It is being called, but config.set and config.write just don't work.

            However, if the app is restartet, all settings that are not valid, are 
            changed to valid values. This is realy wired!
        """       

        if section == 'Math':
            if key == 'operator':

                if set(["+", "-", "*", ":", "%"]).union([str(v) for v in value]) != set(["+", "-", "*", ":", "%"]):
                    Logger.info('App: This choice is forbidden. Returning to default.')
                    self.config.set('Math', 'operator', '*')
                    self.config.write()

                    # Also tried combinations of the following lines:
                    #Clock.schedule_once(partial(self.config.set, 'Math', 'diffclty', value))   # -> set-method misses *args, so dt cannot be catched
                    #self.config.write()
                    #Clock.schedule_once(self.close_settings)
                    #Clock.schedule_once(partial(self.on_config_change, self.config, 'Math', 'diffclty', value))
                    #Clock.schedule_once(self.open_settings, 1)

            if key == 'operator_':
                pass


    def on_config_change(self, config, section, key, value, *args):

        if section == 'Math':

            if key == 'operator':

                Logger.info('App: Your operators via free choice: %s' %value)
                #self.root.calculation_screen.operation = ''.join([str(MathBackEnd.operator_strings.index(p)) for p in list(value)])                

            if key == 'operator_':

                Logger.info('App: Your operators via options: %s' %value)




if __name__ in ('__main__', '__android__'):
    MySettingsApp().run()

1 个答案:

答案 0 :(得分:0)

我们的想法是将SettingsSettingString子类化,这两者都可以在kivy API中找到设置。在SettingString的子类中,定义包含验证的方法_validate。用户输入将保存在self.textinput.text中,有效值应保存在self.value中,无效值只会结束进程(或引发异常)。在Settings的子类中注册一个新类型并将其设置为SettingString的子类。在定义设置的数据时,将在json文件中使用此类型。

# Kivy
from kivy.app import App
from kivy.lang.builder import Builder

from kivy.uix.settings import Settings
from kivy.uix.settings import SettingString
from kivy.uix.settings import InterfaceWithNoMenu
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

from kivy.logger import Logger





JSON_MATH = '''
[
    {
        "type": "complex_operator_string",
        "title": "Operator (free choice)",
        "desc": "Choose the operator. + (addition). - (subtraction). * (multiplication). : (division). % (modulo). You can also choose any combination of those operations to create your own mix.",
        "section": "Math",
        "key": "operator"
    },
    {
        "type": "options",
        "title": "Operator (options)",
        "desc": "Choose the operator. + (addition). - (subtraction). * (multiplication). : (division). % (modulo). You can also choose from three mixes.",
        "options": ["+", "-", "*", ":", "%", "+-", "*:", "+-*:"],
        "section": "Math",
        "key": "operator_"
    }
]
'''

kv_string = """
<MySettingsRoot>:
    orientation: 'vertical'

    Label:
        text: '[b] My Settings App [/b]'
        markup: True

    Button:
        text: 'Settings'
        on_release: app.open_settings()

    Button:
        text: 'Quit'   
        on_release: app.stop()

<ValidatedSettings>:
    interface_cls: 'ValidatedSettingsInterface'
"""



###############################################################################
# Widgets
###############################################################################

class ValidatedSettingsInterface(InterfaceWithNoMenu):  
    pass

class ValidatedSettings(Settings):

    def __init__(self, **kwargs):
        super(ValidatedSettings, self).__init__(**kwargs)
        self.register_type('complex_operator_string', OperatorSetting)

    def add_kivy_panel(self):
        pass

class OperatorSetting(SettingString):

    def __init__(self, **kwargs):
        super(OperatorSetting, self).__init__(**kwargs)

    def _validate(self, instance):
        self._dismiss()    # closes the popup
        try:
            assert set(["+", "-", "*", ":", "%"]).union([str(v) for v in self.textinput.text]) == set(["+", "-", "*", ":", "%"])
            self.value = self.textinput.text
            Logger.info('App: Assertion is true, setting value to textinput')
        except AssertionError:
            Logger.info('App: This choice is forbidden.')
            return



###############################################################################
# Root Widget
###############################################################################

class MySettingsRoot(BoxLayout):
    """ See kv string
    """
    def __init__(self, *args, **kwargs):
        super(MySettingsRoot, self).__init__(*args, **kwargs)




###############################################################################
# App Object
###############################################################################

class MySettingsApp(App):
    """ App object
    """
    def __init__(self, *args, **kwargs):
        super(MySettingsApp, self).__init__(*args, **kwargs)
        self.settings_cls = ValidatedSettings         

    def build(self):
        Builder.load_string(kv_string)
        return MySettingsRoot()

    def build_config(self, config):
        config.setdefaults('Math', {'operator': '+-:%', 'operator_': '*'})

    def build_settings(self, settings):
        settings.add_json_panel('Math', self.config, data=JSON_MATH)



    def on_config_change(self, config, section, key, value, *args):

        if section == 'Math':

            if key == 'operator':

                Logger.info('App: Your operators via free choice: %s' %value)

            if key == 'operator_':

                Logger.info('App: Your operators via options: %s' %value)




if __name__ in ('__main__', '__android__'):
    MySettingsApp().run()