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

Kivy技术问题:如何在BoxLayout中调整按钮的X轴尺寸?

看起来你遇到的问题是因为你的MainWidget默认继承自Widget类,而Widget本身没有内置的布局管理逻辑,导致里面的BoxLayout没有自动占满整个窗口空间,所以你设置的size_hint: .5, .5看起来没生效。

给你两个简单的解决方案:

方案1:让MainWidget继承自布局类

把你的.kv文件里的MainWidget定义改成继承自FloatLayout(或者BoxLayout也可以,FloatLayout更适合这种需要自由定位子控件的场景):

MainWidget:
<MainWidget@FloatLayout>:
    BoxLayout:
        canvas.before:
            Color:
                rgba: (1,0,0,1)
            Rectangle:
                pos: self.pos
                size: self.size
        Button:
            text: "+"
            color: 0,0,0
            size_hint: .5, .5
            pos_hint: {'center_x': .5,'center_y': .5}
            canvas.before:
                Color:
                    rgba: (1,0,1,1)
                Rectangle:
                    size: self.size
                    pos: self.pos

这样BoxLayout会自动占满整个FloatLayout的空间,按钮的size_hint就会按照预期工作——宽度是BoxLayout的一半,高度也是一半,并且居中显示。

方案2:手动绑定BoxLayout的尺寸到MainWidget

如果你坚持要让MainWidget继承自Widget,可以通过绑定BoxLayout的pos和size到父控件(也就是MainWidget)的属性,让它占满整个父控件:

MainWidget:
<MainWidget>:
    BoxLayout:
        pos: self.parent.pos
        size: self.parent.size
        canvas.before:
            Color:
                rgba: (1,0,0,1)
            Rectangle:
                pos: self.pos
                size: self.size
        Button:
            text: "+"
            color: 0,0,0
            size_hint: .5, .5
            pos_hint: {'center_x': .5,'center_y': .5}
            canvas.before:
                Color:
                    rgba: (1,0,1,1)
                Rectangle:
                    size: self.size
                    pos: self.pos

这样BoxLayout的大小就会和MainWidget完全一致,按钮的尺寸设置自然就生效了。

为什么会出现这个问题?

Widget是Kivy里最基础的控件类,它只提供最基本的显示功能,不会自动管理子控件的位置和大小。而像FloatLayout、BoxLayout这类布局控件,内置了布局逻辑,会根据子控件的size_hint和pos_hint自动调整它们的尺寸和位置,所以用布局类作为根控件会更省心。

内容的提问来源于stack exchange,提问作者samy ben

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 12:18:15