Kivy:将原始小部件添加到 GridLayout(而不是图像、按钮等)

Kivy: Add raw Widget to GridLayout (as opposed to Image, Button, etc)

仍在学习 Kivy 的来龙去脉,但我 运行 遇到了一个有趣的问题。假设我有一个 GridLayout,像这样:

class MainApp(App):

    def build(self):
        self.root = GridLayout(cols=2)

        for i in range(4):
            self.root.add_widget(Button(text='Button {}'.format(i)))

        return self.root

我明白了(如预期):


(来源:cachefly.net

然而,当我尝试使每个象限成为动态容器而不是普通的旧 ButtonLabelImage 等时,小部件(像这样):

class Container(Widget):

    def __init__(self, *args, **kwargs):
        _id = kwargs.pop('button_id')
        super(Container, self).__init__(*args, **kwargs)

        self.add_widget(Button(text="Button {}".format(_id)))


class MainApp(App):

    def build(self):
        self.root = GridLayout(cols=2)

        for i in range(4):
            self.root.add_widget(Container(button_id=i))

        return self.root

我明白了:


(来源:cachefly.net

请注意,无论 window 的大小如何,每个小部件都位于左下角并保持较小的尺寸。

添加内置的 Kivy 小部件类型使其工作的原因是什么,但是使用 Widget 对象作为其他 Widget 对象的桶不起作用?

尝试从 kivy.uix.layout.Layout 或其子class之一(例如 kivy.uix.layout.BoxLayout)继承您的 Container class。

来自the Widget docs

The default size of a widget is (100, 100). This is only changed if the parent is a http://kivy.org/docs/api-kivy.uix.layout.html#kivy.uix.layout.Layout. For example, if you add a Label inside a Button, the label will not inherit the button’s size or position because the button is not a Layout: it’s just another Widget.