KIVY ​Properties¶​

Properties¶

Jump to API ⇓

Module: kivy.properties

Added in 1.0.0

The Properties classes are used when you create an EventDispatcher.

Warning

Kivy’s Properties are not to be confused with Python’s properties (i.e. the @property decorator and the <property> type).

Kivy’s property classes support:

Value Checking / Validation

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.

Observer Pattern

You can specify what should happen when a property’s value changes. You can bind your own function as a callback to changes of a Property. If, for example, you want a piece of code to be called when a widget’s pos property changes, you can bind a function to it.

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:

class MyClass(object):
    def __init__(self, a=1.0):
        super(MyClass, self).__init__()
        self.a = a

With Kivy, you can do:

class MyClass(EventDispatcher):
    a = NumericProperty(1.0)

Depth being tracked¶

Only the “top level” of a nested object is being tracked. For example:

my_list_prop = ListProperty([1, {'hi': 0}])
# Changing a top level element will trigger all `on_my_list_prop` callbacks
my_list_prop[0] = 4
# Changing a deeper element will be ignored by all `on_my_list_prop` callbacks
my_list_prop[1]['hi'] = 4

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:

class MyClass(object):
    def __init__(self, a=1):
        super(MyClass, self).__init__()
        self.a_min = 0
        self.a_max = 100
        self.a = a

    def _get_a(self):
        return self._a
    def _set_a(self, value):
        if value < self.a_min or value > self.a_max:
            raise ValueError('a out of bounds')
        self._a = value
    a = property(_get_a, _set_a)

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:

class MyClass(EventDispatcher):
    a = BoundedNumericProperty(1, min=0, max=100)

That’s all!

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:

# simply returns 0 if the value exceeds the bounds
bnp = BoundedNumericProperty(0, min=-500, max=500, errorvalue=0)

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:

# returns the boundary value when exceeded
bnp = BoundedNumericProperty(0, min=-500, max=500,
    errorhandler=lambda x: 500 if x > 500 else -500)

Keyword arguments and __init__()¶

When working with inheritance, namely with the __init__() of an object that inherits from EventDispatcher e.g. a Widget, the properties protect you from a Python 3 object error. This error occurs when passing kwargs to the object instance through a super() call:

class MyClass(EventDispatcher):
    def __init__(self, **kwargs):
        super(MyClass, self).__init__(**kwargs)
        self.my_string = kwargs.get('my_string')

print(MyClass(my_string='value').my_string)

While this error is silenced in Python 2, it will stop the application in Python 3 with:

TypeError: object.__init__() takes no parameters

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.:

class MyClass(EventDispatcher):
    def __init__(self, my_string, **kwargs):
        super(MyClass, self).__init__(**kwargs)
        self.my_string = my_string

or:

class MyClass(EventDispatcher):
    def __init__(self, my_string='default', **kwargs):
        super(MyClass, self).__init__(**kwargs)
        self.my_string = my_string

Alternatively, you could pop the key-value pair from the kwargs dictionary before calling super():

class MyClass(EventDispatcher):
    def __init__(self, **kwargs):
        self.my_string = kwargs.pop('my_string')
        super(MyClass, self).__init__(**kwargs)

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:

class MyClass(EventDispatcher):
    my_string = StringProperty('default')
    def __init__(self, **kwargs):
        super(MyClass, self).__init__(**kwargs)

print(MyClass(my_string='value').my_string)

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:

class MyClass(EventDispatcher):
    a = NumericProperty(1)

def callback(instance, value):
    print('My callback is call from', instance)
    print('and the a value changed to', value)

ins = MyClass()
ins.bind(a=callback)

# At this point, any change to the a property will call your callback.
ins.a = 5    # callback called
ins.a = 5    # callback not called, because the value did not change
ins.a = -1   # callback called

Note

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_<propname>’¶

If you defined the class yourself, you can use the ‘on_<propname>’ callback:

class MyClass(EventDispatcher):
    a = NumericProperty(1)

    def on_a(self, instance, value):
        print('My property a changed to', value)

Warning

Be careful with ‘on_<propname>’. 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:

<MyWidget>:
    Label:
        id: first
        text: 'First label'
    Label:
        id: second
        text: 'Second label'
    Button:
        label: first
        text: self.label.text
        on_press: self.label = second

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.

In 1.9.0, the rebind option has been introduced that will allow the automatic updating of the text when label is changed, provided it was enabled. See ObjectProperty.

APIHide Description ⇑

class kivy.properties.AliasProperty(gettersetter=Nonerebind=Falsewatch_before_use=True**kwargs

Bases: kivy.properties.Property

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:

def get_right(self):
    return self.x + self.width
def set_right(self, value):
    self.x = value - self.width
right = AliasProperty(get_right, set_right, bind=['x', 'width'])

If x were a non Kivy property then you have to return True from setter to dispatch new value of right:

def set_right(self, value):
    self.x = value - self.width
    return True

Usually bind list should contain all Kivy properties used in getter method. If you return True it will cause a dispatch which one should do when the property value has changed, but keep in mind that the property could already have dispatched the changed value if a kivy property the alias property is bound was set in the setter, causing a second dispatch if the setter returns True.

If you want to cache the value returned by getter then pass cache=True. This way getter will only be called if new value is set or one of the binded properties changes. In both cases new value of alias property will be cached again.

To make property readonly pass None as setter. This way AttributeError will be raised on every set attempt:

right = AliasProperty(get_right, None, bind=['x', 'width'], cache=True)

Parameters:

getter: function

Function to use as a property getter.

setter: function

Function to use as a property setter. Callbacks bound to the alias property won’t be called when the property is set (e.g. right = 10), unless the setter returns True.

bind: list/tuple

Properties to observe for changes as property name strings. Changing values of this properties will dispatch value of the alias property.

cache: boolean

If True, the value will be cached until one of the binded elements changes or if setter returns True.

rebind: bool, defaults to False

See ObjectProperty for details.

watch_before_use: bool, defaults to True

Whether the bind properties are tracked (bound) before this property is used in any way.

By default, the getter is called if the bind properties update or if the property value (unless cached) is read. As an optimization to speed up widget creation, when watch_before_use is False, we only track the bound properties once this property is used in any way (i.e. it is bound, it was set/read, etc).

The property value read/set/bound will be correct as expected in both cases. The difference is only that when False, any side effects from the getter would not occur until this property is interacted with in any way because the getter won’t be called early.

Changed in version 1.9.0: rebind has been introduced.

Changed in version 1.4.0: Parameter cache added.

get(selfEventDispatcher obj

link_deps(selfEventDispatcher objunicode name

link_eagerly(selfEventDispatcher obj) → PropertyStorage¶

rebind¶

rebind: ‘int’

set(selfEventDispatcher objvalue

trigger_change(selfEventDispatcher objvalue

class kivy.properties.BooleanProperty(defaultvalue=True**kw

Bases: kivy.properties.Property

Parameters:

defaultvalue: boolean

Specifies the default value of the property.

class kivy.properties.BoundedNumericProperty(*largs**kw

Bases: kivy.properties.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.

bounds¶

Return min/max of the value.

New in version 1.0.9.

get_max(selfEventDispatcher obj

Return the maximum value acceptable for the BoundedNumericProperty in obj. Return None if no maximum value is set. Check get_min for a usage example.

New in version 1.1.0.

get_min(selfEventDispatcher obj

Return the minimum value acceptable for the BoundedNumericProperty in obj. Return None if no minimum value is set:

class MyWidget(Widget):
    number = BoundedNumericProperty(0, min=-5, max=5)

widget = MyWidget()
print(widget.property('number').get_min(widget))
# will output -5

New in version 1.1.0.

set_max(selfEventDispatcher objvalue

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.

Warning

Changing the bounds doesn’t revalidate the current value.

New in version 1.1.0.

set_min(selfEventDispatcher objvalue

Change the minimum value acceptable for the BoundedNumericProperty, only for the obj instance. Set to None if you want to disable it:

class MyWidget(Widget):
    number = BoundedNumericProperty(0, min=-5, max=5)

widget = MyWidget()
# change the minimum to -10
widget.property('number').set_min(widget, -10)
# or disable the minimum check
widget.property('number').set_min(widget, None)

Warning

Changing the bounds doesn’t revalidate the current value.

New in version 1.1.0.

class kivy.properties.ColorProperty(defaultvalue=0**kw

Bases: kivy.properties.Property

  • 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 retrieve color from color name and names definitions can be found at this link. Color can be assigned 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.

class kivy.properties.ConfigParserProperty(defaultvaluesectionkeyconfig**kw

Bases: kivy.properties.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:

class Info(Label):

    number = ConfigParserProperty(0, 'info', 'number', 'example',
                                  val_type=int, errorvalue=41)

    def __init__(self, **kw):
        super(Info, self).__init__(**kw)
        config = ConfigParser(name='example')

The above code creates a property that is connected to the number key in the info section of the ConfigParser named example. Initially, this ConfigParser doesn’t exist. Then, in __init__, a ConfigParser is created with name example, which is then automatically linked with this property. then in kv:

BoxLayout:
    TextInput:
        id: number
        text: str(info.number)
    Info:
        id: info
        number: number.text
        text: 'Number: {}'.format(self.number)

You’ll notice that we have to do text: str(info.number), this is because the value of this property is always an int, because we specified int as the val_type. However, we can assign anything to the property, e.g. number: number.text which assigns a string, because it is instantly converted with the val_type callback.

Note

If a file has been opened for this ConfigParser using read(), then write() will be called every property change, keeping the file updated.

Warning

It is recommend that the config parser object be assigned to the property after the kv tree has been constructed (e.g. schedule on next frame from init). This is because the kv tree and its properties, when constructed, are evaluated on its own order, therefore, any initial values in the parser might be overwritten by objects it’s bound to. So in the example above, the TextInput might be initially empty, and if number: number.text is evaluated before text: str(info.number), the config value will be overwritten with the (empty) text value.

Parameters:

default: object type

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.

key: string type

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.

Whenever a ConfigParser becomes linked with a property, if the section or key doesn’t exist, the current property value will be used to create that key, otherwise, the existing key value will be used for the property value; overwriting its current value. You can change the ConfigParser associated with this property if a string was used here, by changing the name of an existing or new ConfigParser instance. Or through set_config().

**kwargs: a list of keyword arguments

val_type: a callable object

The key values are saved in the ConfigParser as strings. When the ConfigParser value is read internally and assigned to the property or when the user changes the property value directly, if val_type is not None, it will be called with the new value as input and it should return the value converted to the proper type accepted ny this property. For example, if the property represent ints, val_type can simply be int.

If the val_type callback raises a ValueError, errorvalue or errorhandler will be used if provided. Tip: the getboolean function of the ConfigParser might also be useful here to convert to a boolean type.

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.

link_deps(selfEventDispatcher objunicode name

set(selfEventDispatcher objvalue

set_config(selfconfig

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.

The instance to use for listening to and saving property value changes. If None, it disconnects the currently used ConfigParser.

class MyWidget(Widget):
    username = ConfigParserProperty('', 'info', 'name', None)

widget = MyWidget()
widget.property('username').set_config(ConfigParser())

class kivy.properties.DictProperty(defaultvalue=0rebind=False**kw

Bases: kivy.properties.Property

Parameters:

defaultvalue: dict, defaults to {}

Specifies the default value of the property.

rebind: bool, defaults to False

See ObjectProperty for details.

Changed in version 1.9.0: rebind has been introduced.

Warning

Similar to ListProperty, when assigning a dict to a DictProperty, the dict stored in the property is a shallow copy of the dict and not the original dict. See ListProperty for details.

link(selfEventDispatcher objunicode name) → PropertyStorage¶

rebind¶

rebind: ‘int’

set(selfEventDispatcher objvalue

class kivy.properties.ListProperty(defaultvalue=0**kw

Bases: kivy.properties.Property

Parameters:

defaultvalue: list, defaults to []

Specifies the default value of the property.

Warning

When assigning a list to a ListProperty, the list stored in the property is a shallow copy of the list and not the original list. This can be demonstrated with the following example:

class MyWidget(Widget):
    my_list = ListProperty([])

widget = MyWidget()
my_list = [1, 5, {'hi': 'hello'}]
widget.my_list = my_list
print(my_list is widget.my_list)
False
my_list.append(10)
print(my_list, widget.my_list)
[1, 5, {'hi': 'hello'}, 10] [1, 5, {'hi': 'hello'}]

However, changes to nested levels will affect the property as well, since the property uses a shallow copy of my_list.

my_list[2]['hi'] = 'bye'
print(my_list, widget.my_list)
[1, 5, {'hi': 'bye'}, 10] [1, 5, {'hi': 'bye'}]

link(selfEventDispatcher objunicode name) → PropertyStorage¶

set(selfEventDispatcher objvalue

class kivy.properties.NumericProperty(defaultvalue=0**kw

Bases: kivy.properties.Property

It only accepts the int or float numeric data type or a string that can be converted to a number as shown below. For other numeric types use ObjectProperty or use errorhandler to convert it to an int/float.

It does not support numpy numbers so they must be manually converted to int/float. E.g. widget.num = np.arange(4)[0] will raise an exception. Numpy arrays are not supported at all, even by ObjectProperty because their comparison does not return a bool. But if you must use a Kivy property, use a ObjectProperty with comparator set to np.array_equal. E.g.:

class A(EventDispatcher):
    data = ObjectProperty(comparator=np.array_equal)
a = A()
a.bind(data=print)
a.data = np.arange(2)
<__main__.A object at 0x000001C839B50208> [0 1]
a.data = np.arange(3)
<__main__.A object at 0x000001C839B50208> [0 1 2]

Parameters:

defaultvalue: int or float, defaults to 0

Specifies the default value of the property.

wid = Widget()
wid.x = 42
print(wid.x)
42
wid.x = "plop"
 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "properties.pyx", line 93, in kivy.properties.Property.__set__
   File "properties.pyx", line 111, in kivy.properties.Property.set
   File "properties.pyx", line 159, in kivy.properties.NumericProperty.check
 ValueError: NumericProperty accept only int/float

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’).

get_format(selfEventDispatcher obj

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.ObjectProperty(defaultvalue=Nonerebind=False**kw

Bases: kivy.properties.Property

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.
是否kv规则使用这个对象作为一个中级属性在kv规则里, 将更新关联属性当这个对象改变时。

That is the standard behavior is that if there’s a kv rule text: self.a.b.c.d, where ab, and c are properties with rebind False and d is a StringProperty. Then when the rule is applied, text becomes bound only to d. If ab, or c change, text still remains bound to d. Furthermore, if any of them were None when the rule was initially evaluated, e.g. b was None; then text is bound to b and will not become bound to d even when b is changed to not be None.
那是一个标准行为,如果一个kv规则 text: self.a.b.c.d, 在 a, b, 和 c, 都是同 重新绑定

By setting rebind to True, however, the rule will be re-evaluated and all the properties rebound when that intermediate property changes. E.g. in the example above, whenever b changes or becomes not None if it was None before, text is evaluated again and becomes rebound to d. The overall result is that text is now bound to all the properties among ab, or c that have rebind set to True.

**kwargs: a list of keyword arguments

baseclass

If kwargs includes a baseclass argument, this value will be used for validation: isinstance(value, kwargs[‘baseclass’]).

Warning

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.

rebind¶

rebind: ‘int’

扩展

在Kivy框架中,ObjectProperty 是一种特殊的属性类型,它允许你创建对Kivy对象(如按钮、标签等)的引用。这种引用在Kivy的kv语言(一种用于定义用户界面的声明性语言)中特别有用。

ObjectProperty 类的参数 rebind 是一个布尔值,它决定了当属性链中的某个属性发生变化时,是否应该重新评估并重新绑定属性链。

解释

  • defaultvalue: 这是属性的默认值。如果未指定,则默认为None
  • rebind: 如果设置为True,当属性链中的任何ObjectProperty(具有rebind=True)发生更改时,整个链都会重新评估,并可能更改最终绑定到的对象。如果设置为False(默认值),则只有直接绑定的属性(例如上述示例中的d)会保持绑定,即使其上游属性(如abc)发生更改也不会重新评估。
  • baseclass: 这是一个可选的关键字参数,它允许你为ObjectProperty指定一个基类,以便进行类型检查。如果提供了baseclass,那么当你尝试将属性值设置为不是该基类或其子类的实例时,将会引发异常。

示例

假设你有以下Kivy代码:

from kivy.app import App  
from kivy.uix.boxlayout import BoxLayout  
from kivy.uix.button import Button  
from kivy.properties import ObjectProperty  
  
class MyWidget(BoxLayout):  
    a = ObjectProperty(None, rebind=True)  
    b = ObjectProperty(None, rebind=True)  
    c = ObjectProperty(None, rebind=False)  
    d = StringProperty('')  
  
    def __init__(self, **kwargs):  
        super(MyWidget, self).__init__(**kwargs)  
        self.a = SomeOtherWidget()  
        self.a.b = AnotherWidget()  
        self.a.b.c = self  
        self.a.b.c.d = 'Hello, World!'  
  
    # ... 其他方法和属性 ...  
  
class MyApp(App):  
    def build(self):  
        return MyWidget()  
  
# ... 其他代码 ...

在上面的例子中,如果rebindTrue,并且ab在运行时更改(例如,你重新分配了一个新的SomeOtherWidgetself.a),那么任何依赖于self.a.b.c.d的属性或方法都可能需要重新评估,因为整个链都可能已经改变。但是,如果crebindFalse,并且c本身没有更改,那么即使ab更改,依赖于cd的属性或方法也不会重新评估。

注意:为了使属性被视为已更改,并触发任何绑定到该属性的回调,你必须为其分配一个新的Python对象,而不仅仅是修改该对象的内部状态。

class kivy.properties.OptionProperty(*largs**kw

Bases: kivy.properties.Property

options.

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.

For example:

class MyWidget(Widget):
    state = OptionProperty("None", options=["On", "Off", "None"])

options¶

Return the options available.

New in version 1.0.9.

class kivy.properties.Property(defaultvalue**kw

Bases: builtins.object

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:

class MyObject(Widget):

    hello = Property('Hello world')

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:

class MyObject(Widget):

    hello = ObjectProperty(None, allownone=True)

# then later
a = MyObject()
a.hello = 'bleh' # working
a.hello = None # working too, because allownone is True.

Parameters:

default:

Specifies the default value for the property.

**kwargs:

If the parameters include errorhandler, this should be a callable which must take a single argument and return a valid substitute value.

If the parameters include errorvalue, this should be an object. If set, it will replace an invalid property value (overrides errorhandler).

If the parameters include force_dispatch, it should be a boolean. If True, no value comparison will be done, so the property event will be dispatched even if the new value matches the old value (by default identical values are not dispatched to avoid infinite recursion in two-way binds). Be careful, this is for advanced use only.

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.

deprecated: bool

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

bind(selfEventDispatcher objobserver

Add a new observer to be called only when the value is changed.

defaultvalue¶

defaultvalue: object

dispatch(selfEventDispatcher 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:

button = Button()
# get the Property class instance
prop = button.property('text')
# dispatch this property on the button instance
prop.dispatch(button)

fbind(selfEventDispatcher objobserverint reftuple largs=()dict kwargs={}

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.

funbind(selfEventDispatcher objobservertuple largs=()dict kwargs={}

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(selfEventDispatcher obj

Return the value of the property.

link(selfEventDispatcher objunicode name) → PropertyStorage¶

Link the instance with its real name.

Warning

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:

class MyWidget(Widget):
    uid = NumericProperty(0)

In this example, the uid will be a NumericProperty() instance, but the property instance doesn’t know its name. That’s why link() is used in Widget.__new__. The link function is also used to create the storage space of the property for this specific widget instance.

link_deps(selfEventDispatcher objunicode name

link_eagerly(selfEventDispatcher obj) → PropertyStorage¶

set(selfEventDispatcher objvalue

Set a new value for the property.

set_name(selfEventDispatcher objunicode name

unbind(selfEventDispatcher objobserverint stop_on_first=0

Remove the observer from our widget observer list.

unbind_uid(selfEventDispatcher objuid

Remove the observer from our widget observer list bound with fbind using the uid.

class kivy.properties.ReferenceListProperty(*largs**kw

Bases: kivy.properties.Property

For example, if x and y are NumericPropertys, we can create a ReferenceListProperty for the pos. If you change the value of pos, it will automatically change the values of x and y accordingly. If you read the value of pos, it will return a tuple with the values of x and y.

For example:

class MyWidget(EventDispatcher):
    x = NumericProperty(0)
    y = NumericProperty(0)
    pos = ReferenceListProperty(x, y)

get(selfEventDispatcher obj

link(selfEventDispatcher objunicode name) → PropertyStorage¶

link_deps(selfEventDispatcher objunicode name

set(selfEventDispatcher obj_value

setitem(selfEventDispatcher objkeyvalue

trigger_change(selfEventDispatcher objvalue

class kivy.properties.StringProperty(defaultvalue=''**kw

Bases: kivy.properties.Property

Parameters:

defaultvalue: string, defaults to ‘’

Specifies the default value of the property.

class kivy.properties.VariableListProperty(defaultvalue=Nonelength=4**kw

Bases: kivy.properties.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 VariableListProperty is 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.

length¶

length: ‘int’

link(selfEventDispatcher objunicode name) → PropertyStorage¶

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/713721.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

2024年大数据领域的主流分布式计算框架有哪些

Apache Spark 适用场景 以批处理闻名&#xff0c;有专门用于机器学习的相关类库进行复杂的计算&#xff0c;有SparkSQL可以进行简单的交互式查询&#xff0c;也可以使用DataSet&#xff0c;RDD&#xff0c;DataFrame进行复杂的ETL操作。 关键词 处理数据量大批计算微批计算…

[Qt的学习日常]--常用控件1

前言 作者&#xff1a;小蜗牛向前冲 名言&#xff1a;我可以接受失败&#xff0c;但我不能接受放弃 如果觉的博主的文章还不错的话&#xff0c;还请点赞&#xff0c;收藏&#xff0c;关注&#x1f440;支持博主。如果发现有问题的地方欢迎❀大家在评论区指正 目录 一、什么是控…

【2024亲测无坑】Oracle--19C在Centos7上的静默安装(rpm版)

一、Oracle 19c Linux安装&#xff08;Centos 7&#xff09; 1.查看磁盘可用空间及配置ip地址 [rootlocalhost /]# df -h 文件系统 容量 已用 可用 已用% 挂载点 devtmpfs 1.4G 0 1.4G 0% /dev tmpfs 1.4G …

进程信号(下)

上文&#xff1a;进程信号&#xff08;上&#xff09;-CSDN博客 在上篇中&#xff0c;我们讲了关于信号的保存&#xff0c;信号集的操作&#xff0c;那么这篇我们就来看看信号的原理。 目录 1. 键盘产生信号的原理 2. 信号是如何被处理的&#xff1f; 2.1 信号处理的原理 …

深度神经网络——深度学习中的 RNN 和 LSTM 是什么?

引言 自然语言处理和人工智能聊天机器人领域许多最令人印象深刻的进步都是由 递归神经网络&#xff08;RNN&#xff09; 和长短期记忆&#xff08;LSTM&#xff09;网络。 RNN 和 LSTM 是特殊的神经网络架构&#xff0c;能够处理顺序数据&#xff0c;即按时间顺序排列的数据。…

实用软件下载:会声会影2023最新安装包及详细安装教程

会声会影2023的智能工具&#xff0c;使用AI面部识别对效果最好的照片和视频片段进行分析&#xff0c;提取&#xff0c;并编译到可以项目中&#xff0c;将我们的精彩时刻、美好回忆和媒体内容转换为影片。 全新的AR贴纸让视频更具感染力和趣味性&#xff0c;AR贴纸功能可以识别并…

python 实现各种数据分析方法

1、相关性分析 1.1、https://zhuanlan.zhihu.com/p/669355778https://zhuanlan.zhihu.com/p/669355778

Jacob环境探索(兼容性、管理员、DLL位置、VS环境,COM权限)

概述&#xff1a; 最近在生产开发实践出现了很多问题&#xff0c;经过了一系列排查&#xff0c;特做如下总结 探索成果&#xff1a; 1. jacob.dll的建议位置 首先jacob的官网&#xff0c;以及官方GitHub&#xff0c;你可以从这里找到DLL文件&#xff0c;以及相关资料然后DLL文…

WordPress——Argon主题美化

文章目录 Argon主题美化插件类类别标签页面更新管理器文章头图URL查询监视器WordPress提供Markdown语法评论区头像设置发信设置隐藏登陆备份设置缓存插件 主题文件编辑器页脚显示在线人数备案信息(包含备案信息网站运行时间)banner下方小箭头滚动效果站点功能概览下方Links功能…

GitHub Copilot 登录账号激活,已经在IntellJ IDEA使用

GitHub Copilot 想必大家都是熟悉的&#xff0c;一款AI代码辅助神器&#xff0c;相信对编程界的诸位并不陌生。 今日特此分享一项便捷的工具&#xff0c;助您轻松激活GitHub Copilot&#xff0c;尽享智能编码之便利&#xff01; GitHub Copilot 是由 GitHub 和 OpenAI 共同开…

38、基于卷积神经网络(CNN)的车牌自动识别系统(matlab)

1、原理及流程 1&#xff09;原理 CNN&#xff08;卷积神经网络&#xff09;是一种深度学习模型&#xff0c;可以用于图像识别和分类任务。车牌自动识别系统的原理基本上就是使用CNN模型对车牌图像进行处理和识别。 首先&#xff1a;系统需要收集大量的含有车牌的图像数据作…

windows系统,家庭自用NAS。本地局域网 Docker安装nextcloud

windows系统&#xff0c;家庭自用NAS。本地局域网 Docker安装nextcloud 1、docker安装 太简单了&#xff0c;直接去搜一搜。 docker-compose 相关命令 docker-compose down docker compose up -d2、还是使用老的 在你需要挂载的目录下&#xff0c;新建一个文件&#xff0c;…

航顺MCU概览

前言: 截止2023年底,全国有3451家芯片设计公司,已经IPO的就有168家,尚未IPO的3283家中超过一半的年营收在1000万以下,迅猛发展的几年的确有些国产芯片开始站上赛道,这也是国际大背景下的一种必然选择,毕竟突然间出现的大市场需要国产顶上,但资本市场是周期性的,国产替…

港科夜闻 | 香港科大与香港科大(广州)合推红鸟跨校园学习计划,共享教学资源,促进港穗学生交流学习...

关注并星标 每周阅读港科夜闻 建立新视野 开启新思维 1、香港科大与香港科大(广州)合推“红鸟跨校园学习计划”&#xff0c;共享教学资源&#xff0c;促进港穗学生交流学习。香港科大与香港科大(广州)6月14日共同宣布推出“红鸟跨校园学习计划”&#xff0c;以进一步加强两校学…

transformer和Non-local

两者本质上是一个东西&#xff0c;都是用来求自注意力的&#xff0c;但具体而言还是有一些差别&#xff1b; 1&#xff1a;首先说Non-local&#xff0c;它是像素级别的self-attention,算的是图片中各个像素点对指定像素点的影响&#xff1b; 2&#xff1a;transformer我们拿s…

算法人生(22):从“生成对抗网络”看“逆商提升”

​ 在图像生成与编辑、音频合成、视频生成领域里&#xff0c;有一个非常重要的深度学习方法——生成对抗网络&#xff08;简称GANs&#xff09;&#xff0c;它是由两个神经网络组成的模型&#xff0c;分别为生成器&#xff08;Generator&#xff09;和判别器&#xff08;Discr…

移动硬盘数据恢复方法哪个好?六个硬盘恢复,新手也能用!

移动硬盘数据恢复方法哪个好&#xff1f;移动硬盘&#xff0c;作为我们存储重要数据的常用设备&#xff0c;一旦里面的视频、文档、音频等资料突然消失&#xff0c;确实会令人烦恼和担忧。然而&#xff0c;因为数据丢失的原因可能多种多样&#xff0c;因此恢复方法也会有所不同…

【嵌入式DIY实例】-Nokia 5110显示DS3231 RTC数据

Nokia 5110显示DS3231 RTC数据 文章目录 Nokia 5110显示DS3231 RTC数据1、硬件准备与接线2、代码实现本文将介绍如何使用 ESP8266 NodeMCU 板和 DS3231 RTC 模块制作一个简单的数字实时时钟,其中可以使用连接到 NodeMCU 的两个按钮设置时间和日期,并将它们打印在诺基亚 5110 …

Ubuntu server 24 (Linux) 新增磁盘 lvm 动态扩容磁盘空间

1 新增一块硬盘 #查看 sudo fdisk -l #重新分区&#xff0c;转换成lvm类型 sudo fdisk /dev/sdb 2 查看磁盘 df -h3 lvm 配置 #查看lvm逻辑卷 sudo lvdisplay #创建物理卷 sudo pvcreate /dev/sdb1 #扩展卷组 sudo vgextend ubuntu-vg /dev/sdb1 #扩展逻辑卷 sudo lvexte…

【Linux】pycharmgit相关操作

目录 1. git安装配置2. 相关内容3. pycharm连接远程仓库3.1 配置3.2 clone远程仓库3.3 本地仓库上传远程 4. 分支管理4.1 更新代码4.2 新建分支4.3 分支合并4.4 代码比对 5. 版本管理6. 命令行操作6.1 配置git6.2 基础操作6.3 分支操作 1. git安装配置 下载链接&#xff1a;官…