Properties¶
Module: kivy.properties
Added in 1.0.0
The Properties classes are used when you create an EventDispatcher.
属性类们 被使用的 当你创造一个 EventDispatcher
Warning
Kivy’s Properties are not to be confused with Python’s properties (i.e. the @property
decorator and the <property> type).
Kivy 的属性们 是不被拒绝的 同 python的属性们。 (像 @property 装饰器 和<property>类型)
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.
当你分配一个新的值给一个属性,这个值是通过验证和限制被检查的。 举例, 对一个OptionProperty 的验证将确保这个值是在一个可能性优先定义的列表。 对一个NumericPropery 的限制将检查你的值 是一个数字类型。 这放置早期的许多错误。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.
你可以明确指出当你一个属性的值改变时什么应该被发生。 你应该bind 绑定你自己的功能作为一个回调给Property 属性改变。 如果, 举例, 你想一段代码可以被召唤当一个组件的位置属性改变时, 你可以绑定一个功能给它。Better Memory Management 更好的内存管理
The same instance of a property is shared across multiple widget instances.
一个属性的相同的案例被分享通过多个组件的案例。
Comparison Python vs. Kivy¶ Python 和 kivy的比较
Basic example¶ 基础案例
Let’s compare Python and Kivy properties by creating a Python class with ‘a’ as a float property:
让我们比较 python 和Kivy 属性们 通过创建一个Python 类 同 一个浮点属性:
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 # 改变一个上级元素将引发所有 'on_my_list_prop' 回调函数 my_list_prop[0] = 4 # Changing a deeper element will be ignored by all `on_my_list_prop` callbacks # 改变一个更深层的元素将被'on_my_list_prop'回调函数忽视 my_list_prop[1]['hi'] = 4
The same holds true for all container-type kivy properties.
相同的支持True 给所有 容器-类型的 的kivy 属性
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:
如果你像来添加一个check 检查给 一个最小/最大的 值 被允许的 给一个属性, 这是一个可能的执行方案在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)
#这行代码使用Python的 property 装饰器将 _get_a 和 _set_a 方法
#转换为一个属性。这意味着,当你尝试访问或设置 a 属性时,Python会
#自动调用相应的getter或setter方法。
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!
相应的getter或setter方法 是什么意思?
在面向对象编程中,getter和setter方法(或称为访问器和修改器)是用于访问和修改对象内部状态(即其属性的值)的特定方法。这些方法的名称和用途在不同的编程语言和框架中可能有所不同,但基本概念是相似的。
在Python中,特别是当你使用property
装饰器时,getter和setter方法允许你以更受控的方式访问和修改对象的属性。
Getter方法
Getter方法用于返回对象属性的值。它通常不接受任何参数(除了self
),并返回属性的当前值。
Setter方法
Setter方法用于设置对象属性的值。它通常接受一个参数(除了self
),该参数表示要设置的新值。在setter方法内部,你可以添加逻辑来验证新值的有效性,或者在设置新值之前执行其他操作。
使用property
装饰器
在Python中,你可以使用property
装饰器来将getter和setter方法与一个属性关联起来。这允许你像访问普通属性一样访问它们,但实际上是在调用getter或setter方法。
下面是一个使用getter和setter方法以及property
装饰器的示例:
class MyClass:
def __init__(self, a=1):
self._a = a # 使用下划线前缀来表示这是一个“私有”属性
@property
def a(self):
"""Getter方法"""
return self._a
@a.setter
def a(self, value):
"""Setter方法"""
if value < 0 or value > 100:
raise ValueError('a must be between 0 and 100')
self._a = value
# 使用示例
obj = MyClass(50)
print(obj.a) # 调用getter方法,输出:50
obj.a = 150 # 调用setter方法,将引发ValueError,因为150不在0到100之间
obj.a = 75 # 调用setter方法,成功设置_a的值为75
print(obj.a) # 再次调用getter方法,输出:75
在这个示例中,a
是一个属性,但实际上是通过getter和setter方法来访问和修改的。当你尝试获取obj.a
的值时,你实际上是在调用getter方法。当你尝试设置obj.a
的值时,你实际上是在调用setter方法。
@a.setter
在Python中,@a.setter
是一个装饰器,它用于为类中的属性 a
定义一个setter方法。当你想要控制对某个属性的赋值行为时,你可以使用这种方法。具体来说,你可以在setter方法中添加验证逻辑、触发其他操作或执行任何你需要的额外步骤。
在上面的例子中,@a.setter
装饰器被用来定义一个名为 a
的setter方法,该方法允许你设置类的私有属性 _a
的值,但在设置之前会进行一些验证。
这里是一个简单的例子,展示了如何使用 @a.setter
装饰器:
class MyClass:
def __init__(self, a=1):
self._a = a # 使用下划线前缀来表示这是一个“私有”属性
@property
def a(self):
"""Getter方法,返回_a的值"""
return self._a
@a.setter
def a(self, value):
"""Setter方法,设置_a的值,但在此之前会验证value"""
if not isinstance(value, int):
raise ValueError('a must be an integer')
if value < 0 or value > 100:
raise ValueError('a must be between 0 and 100')
self._a = value
# 使用示例
obj = MyClass(50)
print(obj.a) # 调用getter方法,输出:50
# 尝试设置一个非整数值,会触发ValueError
try:
obj.a = "not an integer"
except ValueError as e:
print(e) # 输出:a must be an integer
# 尝试设置一个超出范围的整数值,也会触发ValueError
try:
obj.a = 150
except ValueError as e:
print(e) # 输出:a must be between 0 and 100
obj.a = 75 # 调用setter方法,成功设置_a的值为75
print(obj.a) # 再次调用getter方法,输出:75
在这个例子中,@a.setter
装饰器确保了在设置 a
属性的值时,值必须是一个整数,并且必须在0到100之间。如果尝试设置不满足这些条件的值,将会引发 ValueError
异常。
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:
如果设置一个值在其他方面报一个 值错误, 在这个属性内你有2个选择来操控这个错误。第一个选择是用一个 errorvalue parameter 错误值范围。 一个 错误值是一个替代品作为一个适合的值。
# simply returns 0 if the value exceeds the bounds 简单地返回0如果值超过分界线 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:
第二个选择来使用一个 错误操控范围。 一个 错误操控者 是一个 可调用的 可返回一个合适的(一个单独的变量功能 或者 lambda )代替值。
# returns the boundary value when exceeded 返回边界值 当超过的时候 bnp = BoundedNumericProperty(0, min=-500, max=500, errorhandler=lambda x: 500 if x > 500 else -500)
这样,如果 x
大于 500
,则返回 500
;如果 x
小于 -500
,则返回 -500
;如果 x
在 -500
和 500
之间,则返回 x
本身。
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:
当在不同等级里, 也就是同一个继承自EventDispatcher的对象__init__()方法, 属性们保护你从一个python3的对象错误。 这个错误出现在当你传递关键字参数给对象案例通过一个super():
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:
当这个错误在python2里静默, 它将会在python3里停滞应用程序。
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.:
逻辑上, 为了修理你那问题, 你要么 把 my_string 直接放在 __init__()定义中 作为一个被要求的元素, 或者 作为一个可选择的关键字参数同一个默认值:
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():
或者,你可以放入 键-值 匹配的关键字字典在召唤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:
kivy 属性是更加灵活的,并且可以要求 kwargs.pop() 自动在背景里 (在super() 召唤EventDispatcher内)来阻挡这个干扰。
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 :)
kivy属性是更加简单的来使用。请看下面章节的如何使用它们的案例们。
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.
就像我们一开始说的一样,kivy属性们执行 检测模式。 那意味着你可以bind()绑定一个属性并且拥有你自己的功能被召唤当值改变时。
There are multiple ways to observe the changes.
有许多方式来观察改变。
Observe using bind()¶ 观察使用bind()
You can observe a property change by using the bind() method outside of the class:
你可以观察一个属性改变通过在这个类外使用bind()方法。
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.
属性对象居住在 类层级 并且管理着关系到案例们的值们。 重新委派在层级水平 将会移除属性。 例如, 继续上面的代码, MyClass.a = 5 替代属性对象作为一个简单地整数。
Observe using ‘on_<propname>’¶ 观察使用 'on_<propname>'
If you defined the class yourself, you can use the ‘on_<propname>’ callback:
如果你定义类通过你自己个, 你可以使用回调函数'on_<propname>':
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.
小心‘on_<propname>’.如果你在创建如此一个回调在一个你正在继承的属性, 你必须不能忘记召唤超类功能。
这是一个Python类的代码片段,可能是基于Kivy框架(或类似的库),因为它使用了EventDispatcher
和NumericProperty
,这两者都是Kivy中的特性。我会为你解释这段代码:
1 类定义:
class MyClass(EventDispatcher):
这定义了一个名为MyClass
的类,它继承自EventDispatcher
。EventDispatcher
允许你注册和触发事件,是许多GUI框架和事件驱动系统中的一个核心概念。
2 属性定义:
a = NumericProperty(1)
在类内部,定义了一个名为a
的属性,它是一个NumericProperty
,初始值为1。NumericProperty
是Kivy中的一个特性,允许你轻松地观察和绑定到一个数值属性的变化。
3 事件处理器:
def on_a(self, instance, value):
print('My property a changed to', value)
这是一个特殊命名的方法,它会在a
属性发生变化时被调用。在Kivy中,当属性名以on_
为前缀,后面跟着属性的名称时(例如on_a
对应于属性a
),这个方法将自动被调用作为属性的变化回调。
在这个方法中,instance
指的是触发此事件的实例(在这种情况下,它应该是MyClass
的一个实例),而value
是属性a
的新值。
当a
的值发生变化时,这个方法会打印一条消息,告知我们a
的新值。
总之,这个类MyClass
定义了一个可以观察和响应其变化的数值属性a
。每当a
的值改变时,它都会打印出新的值。
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.
当点击按钮, 尽管列表对象已经被改变给第二个组件,按钮文本将不会改变因为它被直接关联到第一个标签的text property 文本属性
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.
在1.9.0 重新绑定选项已经被介绍了, 重新绑定将允许自动更新 文本 当标签被改变, 提供它作为可能的。
APIHide Description ⇑
class kivy.properties.AliasProperty(getter, setter=None, rebind=False, watch_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.
如果你没找到一个属性类来适合你的需求, 你可以制作你自己的通过创造个性化的Python 的getter 和setter 方法。
Example from kivy/uix/widget.py where x and width are instances of NumericProperty:
kivy/uix/widget.py 案例 x 和宽度 都是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:
如果x是不是一个Kivy 属性,然后你不得不返回True从setter 来执行新的正确值:
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.
通常 bind绑定列表 应该包含 被使用在getter方法里的所有Kivy属性。 如果你返回True, 它将导致一个派遣, 这派遣应该在属性值改变时发生, 但是记住一点 这个属性应该早就被派遣改变的值了如果一个kivy属性是 alias property别名属性 被设置在setter方法里, 其将导致第二个派遣如果setter返回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.
如果你想缓存这个被返回值,使用getter然后通过 cache=True。 这法 getter将只被召唤 如果新的值被设定 或者绑定属性中的一个改变。 在所有的案例里 alias property 联名属性的新值将被再次缓存。
To make property readonly pass None as setter. This way AttributeError will be raised on every set attempt:
为了使属性只读, 输个 None 作为setter。 着法 attributeError 将出现在任何一个设置意图里。
right = AliasProperty(get_right, None, bind=['x', 'width'], cache=True)
Parameters:
getter: function
Function to use as a property getter. 功能来使用作为一个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.
功能来使用作为一个setter属性。 回调函数绑定给alias property 联名属性将不被召唤当属性被设置 (例如 right=10), 除非 setter 返回True。
在 Kivy 中,当使用 AliasProperty
时,如果你提供了 setter 函数并且该 setter 函数返回 True
,那么与该别名属性绑定的回调(callbacks)将会在属性被设置时(例如 right = 10
)被调用。然而,如果 setter 函数返回 None
或者不返回任何值(即默认返回 None
),则不会触发任何回调。
这里有一个简单的例子,展示了如何使用带有 setter 函数的 AliasProperty
,并在 setter 函数中返回 True
来触发回调:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import AliasProperty, NumericProperty
from kivy.lang import Builder
# 定义 MyWidget 类
class MyWidget(Widget):
x = NumericProperty(0)
width = NumericProperty(100)
def get_right(self, instance, value):
return instance.x + instance.width
def set_right(self, instance, value):
# 计算新的 x 值以匹配给定的 right 值
new_x = value - instance.width
# 设置 x 属性,这可能会触发其他绑定到 x 属性的回调
instance.x = new_x
# 返回 True 表示我们想要触发与 right 属性绑定的回调
return True
# 使用 AliasProperty 创建一个名为 right 的别名属性
# 它有一个 getter 函数 get_right 和一个 setter 函数 set_right
right = AliasProperty(get_right, set_right, bind=['x', 'width'])
def on_right(self, instance, value):
print(f"right has changed to {value}")
# 在这里你可以添加其他的 Kivy 事件处理方法或者初始化代码
# 加载 kv 文件(如果有的话)
Builder.load_string('''
<MyWidget>:
Button:
text: 'Set Right to 150'
on_press: root.right = 150
''')
# 创建 Kivy 应用
class TestApp(App):
def build(self):
return MyWidget()
# 运行应用
if __name__ == '__main__':
TestApp().run()
在这个例子中,right
是一个别名属性,它有一个自定义的 setter 函数 set_right
。当 right
属性被设置时(例如 widget.right = 150
),set_right
函数会被调用,并计算新的 x
值以匹配给定的 right
值。然后,它设置 x
属性,这可能会触发其他绑定到 x
属性的回调。最后,由于 set_right
返回 True
,所以与 right
属性绑定的 on_right
回调也会被触发。
在上面的案例中为什么 right 返回的值是150 而不是50呢?setter方法为什么会返回True ? setter方法是否参与计算了呢?
在上面的案例中,right
返回的值是 150
而不是 50
,是因为我们设置了 right
的值为 150
。在 Kivy 中,当我们直接设置 AliasProperty
的值时,Kivy 会调用我们定义的 setter 方法(如果提供了的话)来尝试设置该属性的值。
在 set_right
方法中,我们并没有直接返回 True
,而是首先计算了一个新的 x
值,使得 x + width
等于给定的 right
值。在这个例子中,如果我们设置 right = 150
,并且 width
是 100
,那么 new_x
就会是 150 - 100 = 50
。然后我们将这个新的 x
值设置到实例的 x
属性上。
setter 方法返回 True
是因为我们在 setter 方法内部明确返回了这个值。在 Kivy 中,setter 方法的返回值决定了是否应该触发与该属性绑定的回调。如果 setter 返回 True
,那么与该属性绑定的所有回调都会被触发。如果 setter 返回 None
或不返回任何值(即默认返回 None
),则不会触发任何回调。
setter 方法确实参与了计算过程,但它并没有直接返回 right
的值。相反,它计算了为了保持 right
的值不变而应该设置的 x
的值,并设置了这个 x
值。然后它返回 True
来触发与 right
属性绑定的回调。
所以,当你设置 widget.right = 150
时,set_right
方法会被调用,它会计算 x
应该为 50
以保持 right
的值为 150
,然后设置 x
的值,并返回 True
。接着,任何与 right
属性绑定的回调(如 on_right
)都会被触发。但是 right
的 getter 方法本身并没有被直接调用,因为我们直接设置了 right
的值,而不是通过 getter 方法来获取它的值。
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.
如果True, 值将被缓存直到被绑定的元素改变, 或者如果setter 返回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.
是否 bind绑定属性都被跟踪(划界)在这个属性以任何方式被使用之前
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).
默认, getter 被召唤如果bind属性更新, 或者 如果属性值(除非被缓存的)是只读的。作为一个最优化来提速组件的创建,当watch_before_use 是False, 我们只能跟踪边界属性一旦这个属性被以任何方式使用(它是便捷,被设定/只读 等等)
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.
属性值 只读/设定/划界 将被纠正作为被期待的在两个案例中。 不同处只是当False,任何一边getter的影响将不会呈现直到这个属性是相互作用的在任何方式内,因为getter 不会被提前召唤。
Changed in version 1.9.0: rebind has been introduced.
Changed in version 1.4.0: Parameter cache added.
get(self, EventDispatcher obj)¶
link_deps(self, EventDispatcher obj, unicode name)¶
link_eagerly(self, EventDispatcher obj) → PropertyStorage¶
rebind¶
rebind: ‘int’
set(self, EventDispatcher obj, value)¶
trigger_change(self, EventDispatcher obj, value)¶
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(self, EventDispatcher 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.
返回最大可接受的值给 BoundedNumericProperty 在对象中。 返回None 如果没有最大值被设置。 检查get_min给一个有用的案例。
New in version 1.1.0.
get_min(self, EventDispatcher obj)¶
Return the minimum value acceptable for the BoundedNumericProperty in obj. Return None if no minimum value is set:
返回最小可接收的值给BoundNumericProperty 在对象中。 返回None 如果没有最小值被设置:
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(self, EventDispatcher obj, value)¶
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.
设置最大的可接受值 给BoundedNumericProperty, 只有当是 对象案例。 设置None 如果你想不用它。 检查set_min 来获取一个可以使用的案例。
Warning
Changing the bounds doesn’t revalidate the current value.
改变的边界们 不能使当前值重新生效。
New in version 1.1.0.
set_min(self, EventDispatcher obj, value)¶
Change the minimum value acceptable for the BoundedNumericProperty, only for the obj instance. Set to None if you want to disable it:
改变 最小可接受的值给BoundedNumericProperty, 只有当是对象案例时。 设置None如果你不想使用它:
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)
一个集合 3 或 4 浮点值 在0-1之间(kivy默认) -
a string in the format #rrggbb or #rrggbbaa
一个字符串以#rrggbb 或者 #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.
对象 colormap颜色表 被用来 检索 颜色名字 和 定义可以被在这个link发现的名字。 颜色可以通过不同的方式委派,但是它将被作为ObservableList的在0-1之间的4个浮点数返回。
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.
颜色值将被分派当设置通过索引或者限制,但是当和限制设置,你必须确保限制有4个有在0-1之间着浮点值的组成成分。分派颜色名字作为值现在是被支持的。 值None 是被允许的作为该属性的默认值。
class kivy.properties.ConfigParserProperty(defaultvalue, section, key, config, **kw)¶
Bases: kivy.properties.Property
of a ConfigParser as well as to bind the ConfigParser values to other properties.
一个ConfigParse 和绑定ConfigParser 值给其它的值。
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.
一个ConfigParser 是由许多部分组成的, 每一部分有几个 键和值 同这些键相关联。 ConfigParserProperty 允许你自动监听和改变基于kivy属性的特殊键的值。
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:
举例: 比方说我们想拥有一个输入框 自动书写它的值, 以一个整数作为代表。在一个ConfigParser的信息部分。 并且, 文本输入框 应该更新它的的值从ConfigParser的部分。 最终, 它们的值应该在一个标签里展示。
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:
上部代码在Config信息部分创造了一个同数字键 相关联的。 初始, ConfigParser 并不存在。 然后在__init__ 里, 一个ConfigParser 被同名字案例 一起创造,这个名字案例等会自动地和这个属性关联
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.
你将注意到, 我们不得不 书写 str(info.number), 这是因为这个属性的值总是一个整数, 因为我们特别说明了int 作为val_type。 然而, 我们可以分派任何东西给这个属性, 例如: 数字 number.text, 这可以分派一个字符串, 因为它是可以同val_type回调函数立刻转变
Note
If a file has been opened for this ConfigParser using read(), then write() will be called every property change, keeping the file updated.
如果一个文件已经被打开给这个ConfigParser 使用read(), 然后write() 将被召唤 每当属性改变, 保持这个文件更新。
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(self, EventDispatcher obj, unicode name)¶
set(self, EventDispatcher obj, value)¶
set_config(self, config)¶
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=0, rebind=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(self, EventDispatcher obj, unicode name) → PropertyStorage¶
rebind¶
rebind: ‘int’
set(self, EventDispatcher obj, value)¶
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(self, EventDispatcher obj, unicode name) → PropertyStorage¶
set(self, EventDispatcher obj, value)¶
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(self, EventDispatcher 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=None, rebind=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 a
, b
, 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 a
, b
, 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, 都是同 重新绑定 False的属性 并且d是一个字符串属性。 然后当规则被应用的时候,text 成为了只和d关联。 如果a , b 或者c 改变, text 仍然保存在d中。 另一方面, 如果它们中的任何一个是None 当规则初始时被评估的, 举例: b时None。 然后 text 被绑定给b 并且不会绑定给d 即使当b改变成不是None。 然后tet 被绑定给b 并且将不会成 绑定给d 即使b 改变成为一个None 的值。
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 a
, b
, or c
that have rebind
set to True
.
通过设定 rebind 为True, 然而, 规则将被重新评估的 并且 所有的属性 重新绑定当中级属性改变。 举例, 在上面的案例中, 无论任何时候b 改变 或者成为不是None 如果它之前是None, text 将被再次重新评估 并且成为 和d 有关联的。 总结就是 text 现在绑定给所有的 元素 a b c 这些rebind 设为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.
--扩展
ObjectProperty
是 Kivy(一个流行的Python GUI库,用于构建跨平台的用户界面)中的一个属性类型。它主要用于Kivy应用程序中,特别是那些需要管理对象引用的类中,例如绑定到视图的属性或数据模型。ObjectProperty
提供了以下几个关键特性:
-
defaultvalue: 初始化属性的默认值,如果对象没有被设置,那么默认会使用这个值。
-
rebind: 如果设置为
True
,则当对象被重新绑定(例如,从一个实例替换为另一个实例)时,属性会自动更新,这对于处理可变对象和避免内存泄漏很重要。 -
kw: 其他可能接受的关键字参数,如
allownone
(是否允许属性为空,即None值)等,可以根据实际需求调整。
当你在 Kivy 中定义一个 ObjectProperty
,你可以像操作其他变量一样操作它,但它的行为会更智能,比如它会处理对象的生命周期和属性的自动绑定。举个例子,你可能会在 BoxLayout
的某个视图上定义一个 ObjectProperty
,然后将它关联到一个数据模型,这样当数据模型改变时,视图也会相应地更新。
在 Kivy 中,rebind
参数通常用于 EventDispatcher
类(Kivy 的核心事件处理机制)中的方法,比如 bind()
和 unbind()
方法。这些方法用于绑定或解绑函数到特定的事件上。当你想要在一个对象的方法被重写(即覆盖)的情况下,仍然保持原始绑定的行为,这时候就需要用到 rebind
。
rebind=True
的作用是即使新绑定的函数改变了,原有的事件绑定也不会丢失。当子类继承父类,重写了父类的某个事件处理方法,如果在子类的 __init__
中使用了 rebind=True
,那么原父类方法绑定的回调函数还会继续接收事件,直到你手动解除绑定。
例如:
class Parent(EventDispatcher):
def on_press(self, *args):
print("Parent's on_press")
class Child(Parent):
def on_press(self, *args):
# 重写父类的 on_press 方法
super().on_press(*args)
print("Child's on_press")
parent = Parent()
child = Child()
parent.bind(on_press=parent.on_press) # 正常绑定
# parent.rebind(on_press=parent.on_press) # 如果需要,使用 rebind
# 当 child 的 on_press 被调用,会先执行父类的 on_press,然后执行 child 的
child.dispatch('on_press')
rebind¶
rebind: ‘int’
扩展
在Kivy框架中,ObjectProperty
是一种特殊的属性类型,它允许你创建对Kivy对象(如按钮、标签等)的引用。这种引用在Kivy的kv
语言(一种用于定义用户界面的声明性语言)中特别有用。
ObjectProperty
类的参数 rebind
是一个布尔值,它决定了当属性链中的某个属性发生变化时,是否应该重新评估并重新绑定属性链。
解释
- defaultvalue: 这是属性的默认值。如果未指定,则默认为
None
。 - rebind: 如果设置为
True
,当属性链中的任何ObjectProperty
(具有rebind=True
)发生更改时,整个链都会重新评估,并可能更改最终绑定到的对象。如果设置为False
(默认值),则只有直接绑定的属性(例如上述示例中的d
)会保持绑定,即使其上游属性(如a
、b
或c
)发生更改也不会重新评估。 - 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()
# ... 其他代码 ...
在上面的例子中,如果rebind
为True
,并且a
或b
在运行时更改(例如,你重新分配了一个新的SomeOtherWidget
给self.a
),那么任何依赖于self.a.b.c.d
的属性或方法都可能需要重新评估,因为整个链都可能已经改变。但是,如果c
的rebind
为False
,并且c
本身没有更改,那么即使a
或b
更改,依赖于c
或d
的属性或方法也不会重新评估。
注意:为了使属性被视为已更改,并触发任何绑定到该属性的回调,你必须为其分配一个新的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(self, EventDispatcher obj, observer)¶
Add a new observer to be called only when the value is changed.
defaultvalue¶
defaultvalue: object
dispatch(self, 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:
button = Button() # get the Property class instance prop = button.property('text') # dispatch this property on the button instance prop.dispatch(button)
fbind(self, EventDispatcher obj, observer, int ref, tuple 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(self, EventDispatcher obj, observer, tuple 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(self, EventDispatcher obj)¶
Return the value of the property.
link(self, EventDispatcher obj, unicode 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(self, EventDispatcher obj, unicode name)¶
link_eagerly(self, EventDispatcher obj) → PropertyStorage¶
set(self, EventDispatcher obj, value)¶
Set a new value for the property.
set_name(self, EventDispatcher obj, unicode name)¶
unbind(self, EventDispatcher obj, observer, int stop_on_first=0)¶
Remove the observer from our widget observer list.
unbind_uid(self, EventDispatcher obj, uid)¶
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.
例如, 如果x 和y 都是NumericProperty, 我们可以创造一个 ReferenceListProperty 给位置。 如果你改变位置的值, 它将相应地自动地改变x y地值。 如果你读取了位置的值, 它将返回一个元组同x 和y的值。
For example:
class MyWidget(EventDispatcher):
x = NumericProperty(0)
y = NumericProperty(0)
pos = ReferenceListProperty(x, y)
get(self, EventDispatcher obj)¶
link(self, EventDispatcher obj, unicode name) → PropertyStorage¶
link_deps(self, EventDispatcher obj, unicode name)¶
set(self, EventDispatcher obj, _value)¶
setitem(self, EventDispatcher obj, key, value)¶
trigger_change(self, EventDispatcher obj, value)¶
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=None, length=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.