objectproperty kivy что это
Properties¶
Kivy’s Properties are not to be confused with Python’s properties (i.e. the @property decorator and the
Kivy’s property classes support:
Comparison Python vs. Kivy¶
Basic example¶
Let’s compare Python and Kivy properties by creating a Python class with ‘a’ as a float property:
With Kivy, you can do:
Depth being tracked¶
Only the “top level” of a nested object is being tracked. For example:
The same holds true for all container-type kivy properties.
Value checking¶
If you wanted to add a check for a minimum / maximum value allowed for a property, here is a possible implementation in Python:
The disadvantage is you have to do that work yourself. And it becomes laborious and complex if you have many properties. With Kivy, you can simplify the process:
Error Handling¶
If setting a value would otherwise raise a ValueError, you have two options to handle the error gracefully within the property. The first option is to use an errorvalue parameter. An errorvalue is a substitute for the invalid value:
The second option in to use an errorhandler parameter. An errorhandler is a callable (single argument function or lambda) which can return a valid substitute:
Keyword arguments and __init__()¶
While this error is silenced in Python 2, it will stop the application in Python 3 with:
Logically, to fix that you’d either put my_string directly in the __init__() definition as a required argument or as an optional keyword argument with a default value i.e.:
Alternatively, you could pop the key-value pair from the kwargs dictionary before calling super() :
Kivy properties are more flexible and do the required kwargs.pop() in the background automatically (within the super() call to EventDispatcher ) to prevent this distraction:
Conclusion¶
Kivy properties are easier to use than the standard ones. See the next chapter for examples of how to use them 🙂
Observe Property changes¶
As we said in the beginning, Kivy’s Properties implement the Observer pattern. That means you can bind() to a property and have your own function called when the value changes.
There are multiple ways to observe the changes.
Observe using bind()¶
You can observe a property change by using the bind() method outside of the class:
Property objects live at the class level and manage the values attached to instances. Re-assigning at class level will remove the Property. For example, continuing with the code above, MyClass.a = 5 replaces the property object with a simple int.
Observe using ‘on_
If you defined the class yourself, you can use the ‘on_
Be careful with ‘on_
’. If you are creating such a callback on a property you are inheriting, you must not forget to call the superclass function too.
Binding to properties of properties.¶
When binding to a property of a property, for example binding to a numeric property of an object saved in a object property, updating the object property to point to a new object will not re-bind the numeric property to the new object. For example:
When clicking on the button, although the label object property has changed to the second widget, the button text will not change because it is bound to the text property of the first label directly.
class kivy.properties. Property ( defaultvalue, **kw ) ¶
This class handles all the basic setters and getters, None type handling, the observer list and storage initialisation. This class should not be directly instantiated.
By default, a Property always takes a default value:
The default value must be a value that agrees with the Property type. For example, you can’t set a list to a StringProperty because the StringProperty will check the default value.
None is a special case: you can set the default value of a Property to None, but you can’t set None to a property afterward. If you really want to do that, you must declare the Property with allownone=True :
Specifies the default value for the property.
comparator : callable or None
When not None, it’s called with two values to be compared. The function returns whether they are considered the same.
When True, a warning will be logged if the property is accessed or set. Defaults to False.
Changed in version 1.4.2: Parameters errorhandler and errorvalue added
Changed in version 1.9.0: Parameter force_dispatch added
Changed in version 1.11.0: Parameter deprecated added
Add a new observer to be called only when the value is changed.
dispatch ( EventDispatcher obj ) ¶
Dispatch the value change to all observers.
Changed in version 1.1.0: The method is now accessible from Python.
This can be used to force the dispatch of the property, even if the value didn’t change:
Similar to bind, except it doesn’t check if the observer already exists. It also expands and forwards largs and kwargs to the callback. funbind or unbind_uid should be called when unbinding. It returns a unique positive uid to be used with unbind_uid.
Property.funbind(EventDispatcher obj, observer, tuple largs=
Remove the observer from our widget observer list bound with fbind. It removes the first match it finds, as opposed to unbind which searches for all matches.
get ( EventDispatcher obj ) ¶
Return the value of the property.
link ( EventDispatcher obj, str name ) ¶
Link the instance with its real name.
Internal usage only.
When a widget is defined and uses a Property class, the creation of the property object happens, but the instance doesn’t know anything about its name in the widget class:
link_deps ( EventDispatcher obj, str name ) ¶ set ( EventDispatcher obj, value ) ¶
Set a new value for the property.
unbind ( EventDispatcher obj, observer ) ¶
Remove the observer from our widget observer list.
unbind_uid ( EventDispatcher obj, uid ) ¶
Remove the observer from our widget observer list bound with fbind using the uid.
class kivy.properties. NumericProperty ( defaultvalue=0, **kw ) ¶
Specifies the default value of the property.
Changed in version 1.4.1: NumericProperty can now accept custom text and tuple value to indicate a type, like “in”, “pt”, “px”, “cm”, “mm”, in the format: ‘10pt’ or (10, ‘pt’).
Return the format used for Numeric calculation. Default is px (mean the value have not been changed at all). Otherwise, it can be one of ‘in’, ‘pt’, ‘cm’, ‘mm’.
class kivy.properties. StringProperty ( defaultvalue=», **kw ) ¶
Specifies the default value of the property.
class kivy.properties. ListProperty ( defaultvalue=0, **kw ) ¶
Specifies the default value of the property.
However, changes to nested levels will affect the property as well, since the property uses a shallow copy of my_list.
Specifies the default value of the property.
rebind : bool, defaults to False
Whether kv rules using this object as an intermediate attribute in a kv rule, will update the bound property when this object changes.
**kwargs : a list of keyword arguments baseclass
To mark the property as changed, you must reassign a new python object.
Changed in version 1.9.0: rebind has been introduced.
Changed in version 1.7.0: baseclass parameter added.
class kivy.properties. BooleanProperty ( defaultvalue=True, **kw ) ¶
Specifies the default value of the property.
class kivy.properties. BoundedNumericProperty ( *largs, **kw ) ¶
maximum bound – within a numeric range.
Specifies the default value of the property.
**kwargs : a list of keyword arguments
If a min parameter is included, this specifies the minimum numeric value that will be accepted. If a max parameter is included, this specifies the maximum numeric value that will be accepted.
Return min/max of the value.
New in version 1.0.9.
New in version 1.1.0.
New in version 1.1.0.
Change the maximum value acceptable for the BoundedNumericProperty, only for the obj instance. Set to None if you want to disable it. Check set_min for a usage example.
Changing the bounds doesn’t revalidate the current value.
New in version 1.1.0.
Change the minimum value acceptable for the BoundedNumericProperty, only for the obj instance. Set to None if you want to disable it:
Changing the bounds doesn’t revalidate the current value.
New in version 1.1.0.
If the string set in the property is not in the list of valid options (passed at property creation time), a ValueError exception will be raised.
Specifies the default value of the property.
**kwargs : a list of keyword arguments
Should include an options parameter specifying a list (not tuple) of valid options.
Return the options available.
New in version 1.0.9.
If you don’t find a Property class that fits to your needs, you can make your own by creating custom Python getter and setter methods.
Example from kivy/uix/widget.py where x and width are instances of NumericProperty :
If x were a non Kivy property then you have to return True from setter to dispatch new value of right :
To make property readonly pass None as setter. This way AttributeError will be raised on every set attempt:
Function to use as a property getter.
Properties to observe for changes as property name strings. Changing values of this properties will dispatch value of the alias property.
rebind : bool, defaults to False
Changed in version 1.9.0: rebind has been introduced.
Changed in version 1.4.0: Parameter cache added.
set ( EventDispatcher obj, value ) ¶ trigger_change ( EventDispatcher obj, value ) ¶ class kivy.properties. DictProperty ( defaultvalue=0, rebind=False, **kw ) ¶
Specifies the default value of the property.
rebind : bool, defaults to False
Changed in version 1.9.0: rebind has been introduced.
set ( EventDispatcher obj, value ) ¶ class kivy.properties. VariableListProperty ( defaultvalue=None, length=4, **kw ) ¶
list items and to expand them to the desired list size.
For example, GridLayout’s padding used to just accept one numeric value which was applied equally to the left, top, right and bottom of the GridLayout. Now padding can be given one, two or four values, which are expanded into a length four list [left, top, right, bottom] and stored in the property.
Specifies the default values for the list.
length : int, one of 2 or 4.
Specifies the length of the final list. The default list will be expanded to match a list of this length.
**kwargs : a list of keyword arguments
Not currently used.
Keeping in mind that the default list is expanded to a list of length 4, here are some examples of how VariabelListProperty’s are handled.
New in version 1.7.0.
link ( EventDispatcher obj, str name ) ¶ class kivy.properties. ConfigParserProperty ( defaultvalue, section, key, config, **kw ) ¶
of a ConfigParser as well as to bind the ConfigParser values to other properties.
A ConfigParser is composed of sections, where each section has a number of keys and values associated with these keys. ConfigParserProperty lets you automatically listen to and change the values of specified keys based on other kivy properties.
For example, say we want to have a TextInput automatically write its value, represented as an int, in the info section of a ConfigParser. Also, the textinputs should update its values from the ConfigParser’s fields. Finally, their values should be displayed in a label. In py:
Specifies the default value for the key. If the parser associated with this property doesn’t have this section or key, it’ll be created with the current value, which is the default value initially.
section : string type
The section in the ConfigParser where the key / value will be written. Must be provided. If the section doesn’t exist, it’ll be created.
The key in section section where the value will be written to. Must be provided. If the key doesn’t exist, it’ll be created and the current value written to it, otherwise its value will be used.
config : string or ConfigParser instance.
The ConfigParser instance to associate with this property if not None. If it’s a string, the ConfigParser instance whose name is the value of config will be used. If no such parser exists yet, whenever a ConfigParser with this name is created, it will automatically be linked to this property.
**kwargs : a list of keyword arguments val_type : a callable object
verify : a callable object
Can be used to restrict the allowable values of the property. For every value assigned to the property, if this is specified, verify is called with the new value, and if it returns True the value is accepted, otherwise, errorvalue or errorhandler will be used if provided or a ValueError is raised.
New in version 1.9.0.
Sets the ConfigParser object to be used by this property. Normally, the ConfigParser is set when initializing the Property using the config parameter.
Kivy — еще проще, еще нативнее
Продолжаем серию статей о разработке мобильных приложений с фреймворком Kivy. Сегодня речь пойдет о замечательной библиотеке KivyMD — библиотеке для построения нативного интерфейса в стиле Android Material Design, написанной с использованием и для фреймворка Kivy. Откровенно говоря, лично я бесконечно рад, что отпала необходимость лепить и созерцать кривые, темные и страшные кастомные виджеты в Kivy приложениях. Используя в своих проектах библиотеку KivyMD плюс немного фантазии, вряд ли кто-то сможет визуально отличить, написана ли ваша программа на Java или с использованием фрейворка Kivy и Python.
Скачайте, распакуйте KivyMD, зайдите в корневой каталог распакованного архива и выполните установку:
Далее, установите зависимости для KivyMD:
После установки библиотеки вы можете запустить тестовый пример из скачанного вами и распакованного архива:
После запуска вы увидите приложение, демонстрирующее нативные виджеты и контроллы, которые доступны вам для использования в ваших проектах:
В статье мы не будем останавливаться на каких-то конкретных виджетах библиотеки (их создание и параметры прекрасно описаны в том же самом kitchen_sink.py), а создадим простое демонстрационное приложение «Контакты» с использованием KivyMD. Наше приложение будет уметь создавать контакты и группы, а также добавлять в них созданные контакты. Ну, и попутно более детально осветим некоторые аспекты создания интерфейса приложений в Kivy:
Для простого создания дефолтного проекта на Kivy рекомендую CreatorKivyProject, детальное описание работы с которым описанно в этой статье. Итак, следуя инструкциям в статье по ссылке, проект DemoKivyContacts создан. Откроем файл по пути DemoKivyContacts/libs/uix/kv/startscreen.kv, безжалостно удалим все его содержимое и «нарисуем» стартовый экран своего приложения!
Вот так выглядит разметка данного интерфейса в Kivy-Language:
Properties¶
Kivy’s Properties are not to be confused with Python’s properties (i.e. the @property decorator and the
Kivy’s property classes support:
When you assign a new value to a property, the value is checked against validation constraints. For example, validation for an OptionProperty will make sure that the value is in a predefined list of possibilities. Validation for a NumericProperty will check that your value is a numeric type. This prevents many errors early on.
Better Memory Management
The same instance of a property is shared across multiple widget instances.
Comparison Python vs. Kivy¶
Basic example¶
Let’s compare Python and Kivy properties by creating a Python class with ‘a’ as a float property:
With Kivy, you can do:
Depth being tracked¶
Only the “top level” of a nested object is being tracked. For example:
The same holds true for all container-type kivy properties.
Value checking¶
If you wanted to add a check for a minimum / maximum value allowed for a property, here is a possible implementation in Python:
The disadvantage is you have to do that work yourself. And it becomes laborious and complex if you have many properties. With Kivy, you can simplify the process:
Error Handling¶
If setting a value would otherwise raise a ValueError, you have two options to handle the error gracefully within the property. The first option is to use an errorvalue parameter. An errorvalue is a substitute for the invalid value:
The second option in to use an errorhandler parameter. An errorhandler is a callable (single argument function or lambda) which can return a valid substitute:
Keyword arguments and __init__()¶
While this error is silenced in Python 2, it will stop the application in Python 3 with:
Logically, to fix that you’d either put my_string directly in the __init__() definition as a required argument or as an optional keyword argument with a default value i.e.:
Alternatively, you could pop the key-value pair from the kwargs dictionary before calling super() :
Kivy properties are more flexible and do the required kwargs.pop() in the background automatically (within the super() call to EventDispatcher ) to prevent this distraction:
Conclusion¶
Kivy properties are easier to use than the standard ones. See the next chapter for examples of how to use them 🙂
Observe Property changes¶
As we said in the beginning, Kivy’s Properties implement the Observer pattern. That means you can bind() to a property and have your own function called when the value changes.
There are multiple ways to observe the changes.
Observe using bind()¶
You can observe a property change by using the bind() method outside of the class:
Property objects live at the class level and manage the values attached to instances. Re-assigning at class level will remove the Property. For example, continuing with the code above, MyClass.a = 5 replaces the property object with a simple int.
Observe using ‘on_
If you defined the class yourself, you can use the ‘on_
Be careful with ‘on_
’. If you are creating such a callback on a property you are inheriting, you must not forget to call the superclass function too.
Binding to properties of properties.¶
When binding to a property of a property, for example binding to a numeric property of an object saved in a object property, updating the object property to point to a new object will not re-bind the numeric property to the new object. For example:
When clicking on the button, although the label object property has changed to the second widget, the button text will not change because it is bound to the text property of the first label directly.
If you don’t find a Property class that fits to your needs, you can make your own by creating custom Python getter and setter methods.
Example from kivy/uix/widget.py where x and width are instances of NumericProperty :
If x were a non Kivy property then you have to return True from setter to dispatch new value of right :
To make property readonly pass None as setter. This way AttributeError will be raised on every set attempt:
Function to use as a property getter.
Properties to observe for changes as property name strings. Changing values of this properties will dispatch value of the alias property.
rebind : bool, defaults to False
Changed in version 1.9.0: rebind has been introduced.
Changed in version 1.4.0: Parameter cache added.
Parameters defaultvalue : boolean
Specifies the default value of the property.
maximum bound – within a numeric range.
Parameters default : numeric
Specifies the default value of the property.
**kwargs : a list of keyword arguments
If a min parameter is included, this specifies the minimum numeric value that will be accepted. If a max parameter is included, this specifies the maximum numeric value that will be accepted.
Return min/max of the value.
New in version 1.0.9.
New in version 1.1.0.
New in version 1.1.0.
Change the maximum value acceptable for the BoundedNumericProperty, only for the obj instance. Set to None if you want to disable it. Check set_min for a usage example.
Changing the bounds doesn’t revalidate the current value.
New in version 1.1.0.
Change the minimum value acceptable for the BoundedNumericProperty, only for the obj instance. Set to None if you want to disable it:
Changing the bounds doesn’t revalidate the current value.
New in version 1.1.0.
a collection of 3 or 4 float values between 0-1 (kivy default)
a string in the format #rrggbb or #rrggbbaa
a string representing color name (eg. ‘red’, ‘yellow’, ‘green’)
Object colormap is used to retreive color from color name and names definitions can be found at this link. Color can be assinged in different formats, but it will be returned as ObservableList of 4 float elements with values between 0-1.
Parameters defaultvalue : list or string, defaults to [1.0, 1.0, 1.0, 1.0]
Specifies the default value of the property.
New in version 1.10.0.
Changed in version 2.0.0: Color value will be dispatched when set through indexing or slicing, but when setting with slice you must ensure that slice has 4 components with float values between 0-1. Assingning color name as value is now supported. Value None is allowed as default value for property.
of a ConfigParser as well as to bind the ConfigParser values to other properties.
A ConfigParser is composed of sections, where each section has a number of keys and values associated with these keys. ConfigParserProperty lets you automatically listen to and change the values of specified keys based on other kivy properties.
For example, say we want to have a TextInput automatically write its value, represented as an int, in the info section of a ConfigParser. Also, the textinputs should update its values from the ConfigParser’s fields. Finally, their values should be displayed in a label. In py:
Specifies the default value for the key. If the parser associated with this property doesn’t have this section or key, it’ll be created with the current value, which is the default value initially.
section : string type
The section in the ConfigParser where the key / value will be written. Must be provided. If the section doesn’t exist, it’ll be created.
The key in section section where the value will be written to. Must be provided. If the key doesn’t exist, it’ll be created and the current value written to it, otherwise its value will be used.
config : string or ConfigParser instance.
The ConfigParser instance to associate with this property if not None. If it’s a string, the ConfigParser instance whose name is the value of config will be used. If no such parser exists yet, whenever a ConfigParser with this name is created, it will automatically be linked to this property.
**kwargs : a list of keyword arguments val_type : a callable object
verify : a callable object
Can be used to restrict the allowable values of the property. For every value assigned to the property, if this is specified, verify is called with the new value, and if it returns True the value is accepted, otherwise, errorvalue or errorhandler will be used if provided or a ValueError is raised.
New in version 1.9.0.
Sets the ConfigParser object to be used by this property. Normally, the ConfigParser is set when initializing the Property using the config parameter.
Parameters config : A ConfigParser instance.
Parameters defaultvalue : dict, defaults to <>
Specifies the default value of the property.
rebind : bool, defaults to False
Changed in version 1.9.0: rebind has been introduced.
Parameters defaultvalue : list, defaults to []
Specifies the default value of the property.
However, changes to nested levels will affect the property as well, since the property uses a shallow copy of my_list.
Parameters defaultvalue : int or float, defaults to 0
Specifies the default value of the property.
Changed in version 1.4.1: NumericProperty can now accept custom text and tuple value to indicate a type, like “in”, “pt”, “px”, “cm”, “mm”, in the format: ‘10pt’ or (10, ‘pt’).
Return the format used for Numeric calculation. Default is px (mean the value have not been changed at all). Otherwise, it can be one of ‘in’, ‘pt’, ‘cm’, ‘mm’.
Parameters defaultvalue : object type
Specifies the default value of the property.
rebind : bool, defaults to False
Whether kv rules using this object as an intermediate attribute in a kv rule, will update the bound property when this object changes.
**kwargs : a list of keyword arguments baseclass
To mark the property as changed, you must reassign a new python object.
Changed in version 1.9.0: rebind has been introduced.
Changed in version 1.7.0: baseclass parameter added.
If the string set in the property is not in the list of valid options (passed at property creation time), a ValueError exception will be raised.
Parameters default : any valid type in the list of options
Specifies the default value of the property.
**kwargs : a list of keyword arguments
Should include an options parameter specifying a list (not tuple) of valid options.
Return the options available.
New in version 1.0.9.
This class handles all the basic setters and getters, None type handling, the observer list and storage initialisation. This class should not be directly instantiated.
By default, a Property always takes a default value:
The default value must be a value that agrees with the Property type. For example, you can’t set a list to a StringProperty because the StringProperty will check the default value.
None is a special case: you can set the default value of a Property to None, but you can’t set None to a property afterward. If you really want to do that, you must declare the Property with allownone=True :
Specifies the default value for the property.
comparator : callable or None
When not None, it’s called with two values to be compared. The function returns whether they are considered the same.
When True, a warning will be logged if the property is accessed or set. Defaults to False.
Changed in version 1.4.2: Parameters errorhandler and errorvalue added
Changed in version 1.9.0: Parameter force_dispatch added
Changed in version 1.11.0: Parameter deprecated added
Add a new observer to be called only when the value is changed.
dispatch ( EventDispatcher obj ) ¶
Dispatch the value change to all observers.
Changed in version 1.1.0: The method is now accessible from Python.
This can be used to force the dispatch of the property, even if the value didn’t change:
Similar to bind, except it doesn’t check if the observer already exists. It also expands and forwards largs and kwargs to the callback. funbind or unbind_uid should be called when unbinding. It returns a unique positive uid to be used with unbind_uid.
Property.funbind(EventDispatcher obj, observer, tuple largs=
Remove the observer from our widget observer list bound with fbind. It removes the first match it finds, as opposed to unbind which searches for all matches.
get ( EventDispatcher obj ) ¶
Return the value of the property.
Link the instance with its real name.
Internal usage only.
When a widget is defined and uses a Property class, the creation of the property object happens, but the instance doesn’t know anything about its name in the widget class:
Set a new value for the property.
Remove the observer from our widget observer list.
Remove the observer from our widget observer list bound with fbind using the uid.
Parameters defaultvalue : string, defaults to ‘’
Specifies the default value of the property.
list items and to expand them to the desired list size.
For example, GridLayout’s padding used to just accept one numeric value which was applied equally to the left, top, right and bottom of the GridLayout. Now padding can be given one, two or four values, which are expanded into a length four list [left, top, right, bottom] and stored in the property.
Parameters default : a default list of values
Specifies the default values for the list.
length : int, one of 2 or 4.
Specifies the length of the final list. The default list will be expanded to match a list of this length.
**kwargs : a list of keyword arguments
Not currently used.
Keeping in mind that the default list is expanded to a list of length 4, here are some examples of how VariabelListProperty’s are handled.
VariableListProperty([1]) represents [1, 1, 1, 1].
VariableListProperty([1, 2]) represents [1, 2, 1, 2].
VariableListProperty([‘1px’, (2, ‘px’), 3, 4.0]) represents [1, 2, 3, 4.0].
VariableListProperty(5) represents [5, 5, 5, 5].
VariableListProperty(3, length=2) represents [3, 3].
New in version 1.7.0.