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

Kivy ScrollView中新增的最后一个Item被截断问题求助

解决ScrollView底部Item被截断的问题

问题原因

  • 按钮高度未正确设置:Button指定了size_hint=(0.8, None)但未定义height,也未让文本自动适配高度,导致按钮实际高度计算异常,进而影响GridLayout总高度。
  • GridLayout高度计算逻辑错误:手动通过sum(x.height for x in self.children)计算高度,无法实时响应子控件高度变化,且Kivy中children是倒序存储,可能导致计算偏差。
  • ScrollView位置设置无效:pos_hint: {'x':self, 'y':self}是错误写法,pos_hint需传入0-1的比例值,此设置会导致ScrollView位置偏移,底部内容被遮挡。

修复方案

1. 让Button根据文本自动计算高度

通过text_size限制文本宽度,并绑定height到按钮的纹理高度,确保文本完整显示:

btn = Button(
    text='\n"' + self.root.ids.Kommentar.text + '"\n     ~' + self.root.ids.field.text + '\n',
    size_hint=(0.8, None),
    text_size=(self.root.width * 0.8, None),  # 文本宽度匹配按钮宽度
    halign='center'  # 文本居中对齐
)
# 绑定高度为文本纹理的实际高度
btn.bind(height=lambda _, __: btn.setter('height')(btn, btn.texture_size[1]))
self.root.ids.Zitate.add_widget(btn)

2. 改用GridLayout的minimum_height自动计算总高度

Kivy的GridLayout内置minimum_height属性,会自动累加子控件的高度(含padding和spacing),无需手动计算:

GridLayout:           
    cols:1
    padding: 15 
    spacing:10
    size_hint_y: None
    height: self.minimum_height  # 自动计算总高度
    id: Zitate

3. 修正ScrollView的位置设置

将无效的pos_hint改为正确的比例值,确保ScrollView在父容器内完整显示:

ScrollView:
    size_hint_y: None
    pos_hint: {'x': 0, 'y': 0}  # 左上角对齐父容器
    do_scroll_x: False
    do_scroll_y: True 
    size: root.width, root.height / 1.25 

完整修正代码

Kivy代码

GridLayout: 
    ScrollView:
        size_hint_y: None
        pos_hint: {'x': 0, 'y': 0}
        do_scroll_x: False
        do_scroll_y: True 
        size: root.width, root.height / 1.25 

        GridLayout:           
            cols:1
            padding: 15 
            spacing:10
            size_hint_y: None
            height: self.minimum_height
            id: Zitate

Python代码

btn = Button(
    text='\n"' + self.root.ids.Kommentar.text + '"\n     ~' + self.root.ids.field.text + '\n',
    size_hint=(0.8, None),
    text_size=(self.root.width * 0.8, None),
    halign='center'
)
btn.bind(height=lambda _, __: btn.setter('height')(btn, btn.texture_size[1]))
self.root.ids.Zitate.add_widget(btn)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 03:45:38