Python Kivy布局高度以适应子部件';s高度

Python Kivy布局高度以适应子部件';s高度,python,user-interface,kivy,Python,User Interface,Kivy,我想创建一个布局,其中我有一些类似于BoxLayout的东西,使我能够在布局中创建“行”,并且在每个“行”中,我想使用另一个BoxLayout中的某种东西来创建“列” 柱不需要均匀分布。例如,我想创建一个BoxLayout,其中一列带有方形图像,另一列占据剩余可用宽度 请参见“我的要点”中的代码和屏幕截图: 我在上面的代码中完成了基本结构,但除此之外,我希望BoxLayout的高度与孩子们的高度相适应。 实现这一目标的最佳方法是什么 谢谢 不要使用BoxLayout,使用高度为height:se

我想创建一个布局,其中我有一些类似于BoxLayout的东西,使我能够在布局中创建“行”,并且在每个“行”中,我想使用另一个BoxLayout中的某种东西来创建“列”

柱不需要均匀分布。例如,我想创建一个BoxLayout,其中一列带有方形图像,另一列占据剩余可用宽度

请参见“我的要点”中的代码和屏幕截图:

我在上面的代码中完成了基本结构,但除此之外,我希望BoxLayout的高度与孩子们的高度相适应。

实现这一目标的最佳方法是什么


谢谢

不要使用BoxLayout,使用高度为
height:self.minimum\u height
的GridLayout,并为每个子部件设置手动大小(
size\u hint\u y:None
height:some\u number
)。

不过,我想出了一些技巧,可以根据子部件的高度设置
GridLayout
的高度,两者都要求每行有一个子项。。。因此,制作柱确实需要添加内部网格布局

# kv file or string
<Resizing_GridLayout@GridLayout>:
    cols: 1
    row_force_default: True
    foo: [self.rows_minimum.update({i: x.height}) for i, x in enumerate(reversed(list(self.children)))]
# kv file or string for when above goes funky
<ResizingRow_GridLayout@GridLayout>:
    cols: 1
    height: sum([c.height for c in self.children])
为了完整起见,举一个如何将两者缝合在一起的例子

# ... assuming above have been set, bellow maybe within another layout
Resizing_GridLayout:
    ResizingRow_GridLayout:
        Label:
            height: 30
            text: 'Label One'
        TextInput:
            height: 30
            multiline: False
            write_tab: False
            hint_text: 'Insert one liner'
    ResizingRow_GridLayout:
        Label:
            height: 45
            text: 'Label two'
        Button:
            text: 'Button One'
            height: 60
        GridLayout:
            rows: 1
            height: 25
            Button:
                text: 'Button Two'
            Button:
                text: 'Button three'

更新

#!/usr/bin/env python

from collections import OrderedDict
from kivy.uix.gridlayout import GridLayout
from kivy.clock import Clock


class Adaptive_GridLayout(GridLayout):
    """
    Adaptive height and row heights for grid layouts.

    Note this should not be used as a root layout and '_refresh_grids_y_dimension()' method should be used by
    children widgets that change height to update all attached instances of Adaptive_GridLayout (this layout).

    Copyright AGPL-3.0 2019 S0AndS0
    """

    def __init__(self, grow_cols = False, grow_rows = False, **kwargs):
        super(Adaptive_GridLayout, self).__init__(**kwargs)
        self.grow_cols = grow_cols
        self.grow_rows = grow_rows
        self.trigger_refresh_y_dimension = Clock.create_trigger(lambda _: self._refresh_grids_y_dimension(), 0)

    def _yield_tallest_of_each_row(self):
        """ Yields tallest child of each row within gridlayout. """
        current_tallest = None
        for i, c in enumerate(list(reversed(self.children))):
            if current_tallest is None:
                current_tallest = c

            if c.height > current_tallest.height:
                current_tallest = c

            ## Should work around grids without value for 'cols'
            if self.cols is None or self.cols is 0:
                yield current_tallest
                current_tallest = None
            ## Reached last item of current row... Fizzbuzz!
            elif ((i + 1) % self.cols == 0) is True:
                yield current_tallest
                current_tallest = None

    def _calc_child_padding_y(self, child):
        """ Returns total padding for a given child. """
        ## May be faster than asking permission with an if statement as most widgets seem to have padding
        try:
            child_padding = child.padding
        except AttributeError as e:
            child_padding = [0]

        len_child_padding = len(child_padding)
        if len_child_padding is 1:
            padding = child_padding[0] * 2
        elif len_child_padding is 2:
            padding = child_padding[1] * 2
        elif len_child_padding > 2:
            padding = child_padding[1] + child_padding[3]
        else:
            padding = 0

        return padding

    def _calc_min_height(self):
        """ Returns total height required to display tallest children of each row plus spacing between widgets. """
        min_height = 0
        for c in self._yield_tallest_of_each_row():
            min_height += c.height + self._calc_child_padding_y(child = c) + self.spacing[1]
        return min_height

    def _calc_rows_minimum(self):
        """ Returns ordered dictionary of how high each row should be to accommodate tallest children of each row. """
        rows_minimum = OrderedDict()
        for i, c in enumerate(self._yield_tallest_of_each_row()):
            rows_minimum.update({i: c.height + self._calc_child_padding_y(child = c)})
        return rows_minimum

    def _refresh_height(self):
        """ Resets 'self.height' using value returned by '_calc_min_height' method. """
        self.height = self._calc_min_height()

    def _refresh_rows_minimum(self):
        """ Resets 'self.rows_minimum' using value returned by '_calc_rows_minimum' method. """
        self.rows_minimum = self._calc_rows_minimum()

    def _refresh_grids_y_dimension(self):
        """ Updates 'height' and 'rows_minimum' first for spawn, then for self, and finally for any progenitors. """
        spawn = [x for x in self.walk(restrict = True) if hasattr(x, '_refresh_grids_y_dimension') and x is not self]
        for item in spawn:
            item._refresh_rows_minimum()
            item._refresh_height()

        self._refresh_rows_minimum()
        self._refresh_height()

        progenitors = [x for x in self.walk_reverse() if hasattr(x, '_refresh_grids_y_dimension') and x is not self]
        for progenitor in progenitors:
            progenitor._refresh_rows_minimum()
            progenitor._refresh_height()

    def on_children(self, instance, value):
        """ If 'grow_cols' or 'grow_rows' is True this will grow layout that way if needed instead of erroring out. """
        smax = self.get_max_widgets()
        widget_count = len(value)
        if smax and widget_count > smax:
            increase_by = widget_count - smax
            if self.grow_cols is True:
                self.cols += increase_by
            elif self.grow_rows is True:
                self.rows += increase_by
        super(Adaptive_GridLayout, self).on_children(instance, value)

    def on_parent(self, instance, value):
        """ Some adjustments maybe needed to get top row behaving on all platforms. """
        self.trigger_refresh_y_dimension()

上面是我发布的一个项目,它来自一个更大的项目,可能适合也可能不适合那些希望在Python方面有更多逻辑来更新维度的人。检查
自述文件以了解在另一个项目中安装的提示。

对于我来说,使用高度为self.minimum\u height的GridLayout,然后为每个子小部件设置手动大小(size\u hint\u y:None和height:some\u number),使小部件定位到根窗口的底部。真的不知道为什么


但是,使用高度为root.height的GridLayout,然后为每个子小部件设置手动大小(size\u hint\u y:None和height:some\u number),可以得到正确的顶部锚定小部件。

为什么同时需要height和size\u hint?@糟糕,我认为您还需要在
GridLayout
中设置
size\u hint\u y:None
,不仅在children@zwep,因为kivy尊重
大小提示
而不是
大小
,这意味着与直接像素大小相关的所有内容(包括
高度
宽度
)都将被忽略,除非相应的
大小提示
设置为
。Kivy是第一个响应构建的,因此大小提示是优先考虑的。如果
resizinggrow\u GridLayout
包含一个动态向自身添加子项的小部件,这似乎不起作用。我可能误解了你的意思。我需要先了解self.calc_height()
是什么,然后再在一个更大的模型上尝试,在这个模型中,动态添加的子对象可以更改大小。@FergusWyrm是的,我可以更明确一点。。。检查更新并链接到我为跟踪此功能而发布的GitHub项目。。。在你的PasteBin链接中,Line
24
是一个问题点,Kivy
kv
文件中的
foo:stuff
是一种在实例化时运行某些东西的黑客方式,尽管Line
71
可能会做类似的事情,但实际上这样的东西应该是
def
初始化(又名类方法/函数)。。。这意味着可以
def calc_height(self):…
这样其他方法可以调用
self.cal_height()
instance.cal_height()
foo。我让foo在builder和类函数中表现出相同的行为。我确实让它更可靠地显示了这种奇怪的行为。尝试禁用
self。在
ResizingFrame
中触发刷新维度()
,并将lorum ipsum粘贴到拉伸标签中。这应该根据需要从子级调用self.trigger\u refresh\u y\u dimension()。然后你可以看到它只是稍微向下移动了一下标签。我发现
Adaptive\u GridLayout
有一些问题#1:尽管在
\u refresh\u height()
中声明高度没有改变,但高度没有改变#2
填充
被错误地添加到任何尺寸估算中。填充是高度的一部分,不应考虑在内。将
self.size\u hint\u y=None
添加到
\u init\u()
修复了问题1。我必须找到尺寸计算错误的确切位置,以解决问题2。我怀疑还有一个未诊断的问题与
行有关。