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

如何将Kivy按钮居中放置?X坐标设置失效问题求助

问题原因
  • KV代码中存在属性拼写错误:orientartion 正确拼写应为 orientation,拼写错误导致BoxLayout没有按预期切换为垂直排列,保持了默认的水平排列逻辑。
  • BoxLayout为自动排列类布局,会自动管控内部子组件的位置,子组件上设置的pos_hint位置属性不会生效,pos_hint仅在FloatLayout、RelativeLayout、Widget(基础无布局逻辑的组件)这类支持自由定位的父容器下生效。
修正方案

方案1:删除冗余BoxLayout(更简单)

直接将按钮作为Tally的子组件即可,Tally继承自Widget,天然支持子组件的pos_hint定位,修改后的KV代码如下:

<Tally>
    Button:
        text:"Count"
        size_hint: (None, None)
        height: 70
        width: 400
        pos_hint: {"center_x":.5,"center_y":.3}

方案2:保留BoxLayout,通过布局属性调整位置

如果确实需要保留BoxLayout结构,可以通过BoxLayout的padding、alignment属性调整按钮位置,无需给按钮设置center_y相关的pos_hint,参考代码如下:

<Tally>
    BoxLayout:
        orientation:"vertical"
        size: root.width,root.height
        # 底部设置内边距,把按钮往上推到对应高度
        padding: [0, 0, 0, 180]
        Button:
            text:"Count"
            size_hint: (None, None)
            height: 70
            width: 400
            pos_hint: {"center_x":.5}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 04:45:10