gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:57:09 25 4
gpt4 key购买 nike

如果您使用 Kivy 提供的 ConfigParser/Settings 并添加您自己在 json 中定义的设置,那么您只有两种类型的安全设置:“type”:“options”和“type”:“bool”。原因是,其他类型将为用户提供一个文本输入小部件,他们可以在其中输入他们喜欢的任何内容。例如。 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() 。但这不起作用,或者至少它不像我期望的那样起作用:

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

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

Google 搜索“Kivy 输入验证”仅产生一个 stackoverflow 问题,且没有答案。另外这个问题是关于普通的文本输入小部件。然而,我关心的文本输入小部件是某些 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()

最佳答案

这个想法是对 SettingsSettingString 进行子类化,两者都可以在 kivy API 中找到。用于设置。在SettingString 的子类中,定义一个包含验证的方法_validate。用户输入将保存在 self.textinput.text 中,有效值应保存在 self.value 中,无效值只会结束进程(或引发异常(exception))。在 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()

关于python - 清理/验证 Kivy 设置用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49514950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com