例如,我有一个类和相应的KV描述,如下所示。明确指定drag_rectangle
时-拖动有效。但是,当我在此处放置属性node_drag_rect
的调用时,它不是。为什么?
Builder.load_string('''
<W@Widget>:
drag_rectangle: self.x, self.y, self.width, self.height # It works
drag_rectangle: self.node_drag_rect # It doesn't works
''')
class W(DragBehavior, Widget):
@property
def node_drag_rect(self):
return (self.x + 10, self.y + 10, self.width - 20, self.height - 20)
答案 0 :(得分:0)
最后,我找到了应该怎么做。不幸的是,Kivy的文档很差,尤其是在可观察属性声明的一部分中。
下面的示例如何将小部件的Color
绑定到Python属性:
Builder.load_string(f'''
<Interface>:
canvas.before:
Color:
rgba: self.color
''')
class Interface(Widget):
# HERE property should be declared on class level
# not as usual - in initializer via self.color = ....
color = ListProperty(palette.PIN_BG_COLOR) # PIN_BG_COLOR = (.5, .5, 1, 1)
def __init__(self, **kwargs):
super(InterfaceBase, self).__init__(**kwargs)
将属性移到类级别后,所有绑定都可以正常工作。并且不要忘记使用Kivy的可观察属性,而不是Python的属性。
答案 1 :(得分:-1)
1)您的kv语法错误,请使用<W>
创建要与Python类定义一起使用的规则。
2)kv创建自动绑定以在属性的依存关系更改时更新属性,例如在您的第一个drag_rectangle: self.x, ...
中,当self.x
更改时,它将重新计算drag_rectangle。在第二种情况下,它无法知道self.node_drag_rect
何时更改,因此永远不会重新计算结果。这可能会导致图形显示错误。