You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Kivy中去除两个BoxLayout布局之间的空白间隔

问题原因

两个BoxLayout之间的空白是由你给Button设置的size_hint: .1, .3参数导致的:该参数的第二个值代表控件在y轴方向占直接父容器的比例,你设置为0.3意味着每个Button高度只占所属父BoxLayout的30%,剩余70%的空白会默认均匀分布在BoxLayout的上下区域,两个相邻BoxLayout的相邻空白区域拼接就形成了你看到的间隔。
你之前尝试给BoxLayout设置size_hint: None,None和固定尺寸但无效,是因为没有同步调整内部Button的高度占比,即使父容器缩小,Button仍只占父容器30%高度,还是会产生内部留白。

修复方案

你可以直接修改Button的size_hint_y为1,让Button撑满所属BoxLayout的高度即可消除间隔,如果需要控制按钮高度,直接给每个子BoxLayout设置固定高度或者高度占比即可。
修改后的KV代码参考如下:

<BoxLayoutExample>:
    orientation: "vertical"
    Label:
        text: "0"
        font_size: "30dp"
        # 给显示区域单独设置高度占比,避免和按钮区域抢空间
        size_hint_y: 0.2
    BoxLayout:
        orientation: "horizontal"
        size_hint_y: 0.4
        Button:
            text: "7"
            size_hint: .1, 1
        Button:
            text: "4"
            size_hint: .1, 1
        Button:
            text: "1"
            size_hint: .1, 1

    BoxLayout:
        orientation: "horizontal"
        size_hint_y: 0.4
        Button:
            text: ","
            size_hint: .1, 1
        Button:
            text: "0"
            size_hint: .1, 1
        Button:
            text: "="
            size_hint: .1, 1

如果需要进一步缩小间隔,还可以给两个子BoxLayout设置padding: 0和spacing: 0,避免默认内边距带来的额外间隙。

内容的提问来源于stack exchange,提问作者Max La Monica

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 06:24:05