Kivy-Image 仅在 运行 时间居中

Kivy-Image only centered some of the time at run time

我有一个带有按钮的 GridLayout 和要在按钮内显示的图像。当我 运行 我的应用程序时,按钮中的图像有时居中,有时不居中。为什么?我认为它应该始终居中。

.kv 文件:

MyLayout:
    cols: 2                
    height: self.minimum_height
    pos: root.pos

    Button:
        size_hint_y: None
        height: self.parent.width/2
        Image:
            source: 'Images/employee/userprofile.png'
            size: self.parent.size
            center_x: self.parent.center_x
            center_y: self.parent.center_y

下图是我每次都期待的:

这是我有时得到的:

这是 center_xrighttop 等别名属性的常见问题。在 kv 中设置它们不会自动绑定到小部件的大小 (将它添加到 kivy 并不像听起来那么微不足道),所以虽然图像一开始是正确定位的,但如果之后调整大小,则位置不会更新,因为 parent 的 pos 没有改变,只有 children 的尺码!幸运的是,在这种情况下,代码似乎有一半时间有效的情况并不少见,具体取决于特定 运行.

中的调度时间

无论如何,解决方案非常简单,在绑定中显式引用 children 的大小,因此每次更改时都会重新计算表达式。

        center_x: self.width and self.parent.center_x
        center_y: self.height and self.parent.center_y