Kivy:你如何通过 .py 代码设置一个小部件相对于其父级高度的高度?

Kivy : How do you set a widget height relative to its parent 's height from the .py code?

在 Kivi 中是否可以设置 Widget 相对于父级高度的高度?

例如:假设我要放置一个矩形,然后在里面放置三条线,每条线等于矩形高度的1/3,这样三条线堆积起来就可以填满矩形:

我会采用这种方法

Python 文件

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ReferenceListProperty,ObjectProperty

class MyLine(Widget):
    y = NumericProperty(0)

class MyRectangle(Widget):
    line0 = ObjectProperty(0)
    line1 = ObjectProperty(0)
    line2 = ObjectProperty(0)
    def placeLines(self):
        self.line0.y = 0
        self.line1.y = self.height * 1/3
        self.line2.y = self.height * 2/3

class TestApp(App):
    def build(self):
        myRectangle = MyRectangle()
        myRectangle.placeLines()
        return myRectangle

if __name__ == '__main__':
    TestApp().run()

.KV 文件

#:kivy 1.1.1

<MyLine>:
    canvas:
        Color:
            rgba:1,0,0,1
        RoundedRectangle:
            radius:[5.0,]
            pos: self.x, self.y
            size:self.width,self.height

<MyRectangle>:
    size:root.width, root.height
    line0 : MyLine0
    line1:MyLine1
    line2:MyLine2
    canvas:
        Color:
            rgba:0,0,1,1
        Line:
            width:2
            rectangle:(self.x,self.y,self.width,self.height)
    
    MyLine:
        id:MyLine0
        size:self.parent.width, self.parent.height/3
    MyLine:
        id:MyLine1
        size:self.parent.width, self.parent.height/3
    MyLine:
        id:MyLine2
        size:self.parent.width, self.parent.height/3`

只有这样才能使线条在矩形底部堆叠在一起。

如何设置高度的 Y 位置,使高度等于矩形 当前 大小的 0、1/3 和 2/3?

当前结果截图:

问题是在build()方法里面调用placeLines()的时候,MyRectangleheight还没有设置,所以它的值还是默认 100。这导致 MyLine 个实例被放置在 033.3366.66 的 y 值处。定位线条的更好方法是将 placeLines() 绑定到 MyRectanglesize。您可以通过修改 TestApp:

class TestApp(App):
    def build(self):
        myRectangle = MyRectangle()
        myRectangle.bind(size=myRectangle.placeLines)
        # myRectangle.placeLines()
        return myRectangle

并且必须调整 placeLines() 方法以允许 bind 通过允许额外的参数进行调用:

def placeLines(self, *args):
    self.line0.y = 0
    self.line1.y = self.height * 1/3
    self.line2.y = self.height * 2/3