在 Kivy 中计算相对于其他对象的属性

Calculating Properties Relative to Other Objects in Kivy

我是第一次尝试使用 Kivy。我使用

从外部文件导入了一个函数
#:import centerAlign helperFunctions.centerAlign

我的函数 (centerAlign) 如下所示:

def centerAlign(elem, parent):
    pos = [parent.width/2-elem.width/2, parent.height/2-elem.height/2]
    return pos

它的实现如下所示:

    GridLayout:
        cols: 2
        spacing: 10
        size_hint: 0.5, 0.25
        pos: centerAlign(self, root)

这失败了,因为它正在计算两个元素(root 和 GridLayout)的高度和宽度均为 100。但是,我知道这应该有效,因为当我说:

    GridLayout:
        cols: 2
        spacing: 10
        size_hint: 0.5, 0.25
        pos: [root.width/2-self.width/2, root.height/2-self.height/2]

效果很好!所以我真的不明白这里发生了什么。我对 Python 有点陌生,所以希望这很简单,经验丰富的老手可以提供一些启发。提前致谢!

pos: [root.width/2-self.width/2, root.height/2-self.height/2]

当kv解析这一行时,可以看到在root.width、root.height、self.width或self.height时需要更新pos更改,因为它们都在这里引用。自动创建绑定以实现此目的。

 pos: centerAlign(self, root)

此行中没有任何可绑定的属性,因此在任何更改时都不会更新。因此,您只能根据 width/height 的初始值获得结果,即 100。

要解决这个问题,请在 kv 行中引用您想要绑定的属性 编写一些其他代码来创建您想要的绑定。