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

Kivy ScrollView无法滚动求助:动态生成按钮列表无法滚动

解决Kivy ScrollView无法滚动的问题

问题核心是未正确配置可滚动内容的高度自适应逻辑:当布局设置size_hint_y: None时,必须让布局根据子控件自动计算高度,否则内容高度会和ScrollView视口高度一致,导致无法触发滚动。

修改Kivy文件的关键代码

给ScrollView内的根BoxLayout和动态添加按钮的GridLayout添加高度绑定,让它们自动适配内容高度:

<List_of_days>:
    grid: grid
    ScrollView:
        do_scroll_x: False
        BoxLayout:
            size_hint_y: None
            height: self.minimum_height  # 让BoxLayout高度适配所有子控件总高度
            orientation: 'vertical'
            Button:
                size_hint_y: None
                height: 50  # 手动设置返回按钮固定高度
                text: "Назад"
                on_press:
                    app.sm.current = 'menu'
            BoxLayout:
                size_hint_y: None
                height: 50  # 设置ToggleButton容器固定高度
                ToggleButton:
                    text: '7 дней'
                    group:'number_of_days'
                    id: btn_7days
                ToggleButton:
                    id:btn_30days
                    text: '30 дней'
                    group:'number_of_days'
                ToggleButton:
                    id:btn_all_days
                    text: 'Все'
                    group:'number_of_days'
            GridLayout:
                size_hint_y: None
                height: self.minimum_height  # 让GridLayout根据按钮数量自动计算高度
                id:grid
                padding: 10,10
                spacing: 5
                row_default_height:100
                cols: 3

逻辑说明

  • 对于size_hint_y: None的布局,height: self.minimum_height会让布局高度等于所有子控件所需的最小高度总和,确保内容能完整展开。
  • 固定高度的控件(如返回按钮、ToggleButton容器)需要手动设置height,避免布局高度计算异常。
  • 当你在Python代码中循环添加按钮到GridLayout时,GridLayout会自动更新minimum_height,进而触发高度调整,让ScrollView识别到内容高度超过视口,允许正常滚动。

内容的提问来源于stack exchange,提问作者Николай Пильчук

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 17:57:27