指令行为的解释

Explanation of Instructions behaviour

我是 Python 的新手,我不了解 Kivy Instruction(s) 使用的魔法。例如,按照文档,我以这种方式开发了我的(天真的)布局颜色背景扩展

class BoxLayoutColor(BoxLayout) :
    def __init__(self, color = (0,0,0,1), **kwargs):
        super(BoxLayoutColor, self).__init__(**kwargs)
        with self.canvas.before:
            (r,g,b,a) = color
            Color(r,g,b,a)
            self.rect = Rectangle(size=self.size, pos=self.pos)
            self.bind(size=self._update_rect, pos=self._update_rect)
    def _update_rect(self, instance, value):
        self.rect.pos = instance.pos
        self.rect.size = instance.size

它似乎有效,但我想知道构造函数 Color()(因为它是一个构造函数,我是对的?)如何影响上下文。一定有一些隐含的东西我无法从 Python 关于 with 语句的文档中发现...

此外,还有一种方法可以将该功能分组以供其他布局重用?

with 语句是一种通用的 python 语法,它调用您传递给它的对象的某些特殊方法(在本例中为 self.canvas.before)。发生这种情况时,kivy 的 canvas 会在某处设置一个全局变量,并在 with 语句结束时取消设置。当 Instructions 被实例化时,他们检查这个变量是否被定义,如果是,然后自动将自己添加到给定的 canvas.

And also, there is a way to group that functionality to be reused for other layouts ?

Kivy 不支持任何小部件操作的这种语法,尽管添加它可能并不难。我们主要使用kv语言代替,它还有其他优点。