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

Kivy布局无法铺满全屏,尺寸显示异常求助

解决Kivy布局无法覆盖整个屏幕的问题

你的MainWidget继承自Widget,而Widget默认的size_hint是(None, None),默认尺寸为100x100。即便子BoxLayout设置了size_hint: (1,1),它也只会填充MainWidget的100x100区域,所以布局只显示一小部分。

方案一:让MainWidget继承布局类(推荐)

直接将MainWidget的父类从Widget改为BoxLayout,布局类默认会自动占满窗口:

修改后的main.py:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout

class MainWidget(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

class TestApp(App):
    def build(self):
        return MainWidget()

if __name__ == "__main__":
    app = TestApp()
    app.run()

对应的Test.kv可以简化:

<MainWidget>:
    orientation: 'horizontal'

    BoxLayout:
        Label:
            id: the_number
            text: "1"

    BoxLayout:
        orientation: 'vertical'
        padding: 2

        Button:
            id: count_up
            text: "+"

        Button:
            id: count_down
            text: "-"

方案二:保持MainWidget继承Widget,强制占满窗口

如果要保留MainWidget继承Widget,需要在kv规则中给MainWidget设置size_hint: (1,1),同时让子BoxLayout绑定根部件的尺寸:

修改后的Test.kv:

<MainWidget>:
    size_hint: (1,1)
    BoxLayout:
        orientation: 'horizontal'
        size: root.size
        pos: root.pos

        BoxLayout:
            Label:
                id: the_number
                text: "1"

        BoxLayout:
            orientation: 'vertical'
            padding: 2

            Button:
                id: count_up
                text: "+"

            Button:
                id: count_down
                text: "-"

内容的提问来源于stack exchange,提问作者Daniel Rodríguez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 09:01:27