Kivy中ScrollView嵌套GridLayout无法滚动问题求助
问题描述
我已经在网上搜了30分钟找解决办法,但网上的示例都不管用。试过给GridLayout设置自定义高度,也测试过别人用的各种参数,都没效果。我还把ScrollView的代码单独放到另一个文件里运行,滚动功能还是不正常。我觉得.py文件和这部分无关,因为这部分程序没用到相关代码,如果需要.py文件或更多kv代码,我再提供,谢谢:)
相关kv代码
<TrainingPlans> name: "trainingplans" ScrollView: size_hint_y: .85 pos_hint: {"x": 0, "y": .15} do_scroll_x: False do_scroll_y: True GridLayout: size: (root.width, root.height) size_hint_x: None size_hint_Y: None cols: 2 height: self.minimum_height row_default_height: 150 row_force_default: True Label: text: "training1" Button: size_hint: .3, 1 background_normal: "training_programs/unknown.jpeg" Label: text: "training2" Button: size_hint: .3, 1 background_normal: "training_programs/unknown.jpeg" Label: text: "training3" Button: size_hint: .3, 1 background_normal: "training_programs/unknown.jpeg" Label: text: "training4" Button: size_hint: .3, 1 background_normal: "training_programs/unknown.jpeg" Label: text: "training5" Button: size_hint: .3, 1 background_normal: "training_programs/unknown.jpeg" Label: text: "training6" Button: size_hint: .3, 1 background_normal: "training_programs/unknown.jpeg" Label: text: "training7" Button: size_hint: .3, 1 background_normal: "training_programs/unknown.jpeg" Label: text: "training8" Button: size_hint: .3, 1 background_normal: "training_programs/unknown.jpeg" Label: text: "training9" Button: size_hint: .3, 1 background_normal: "training_programs/unknown.jpeg" FloatLayout: size_hint: 1, .15 Button: text: "Back" size_hint: .3, .8 pos_hint: {"x": .01, "y": .06} on_release: app.root.current = "mainwindow" root.manager.transition.direction = "right"
解决方法
你的ScrollView滚动失效是因为GridLayout的参数有两处关键问题:
- 属性名拼写错误:
size_hint_Y是大写Y,Kivy的属性名是小写的size_hint_y,这个错误会导致该属性不生效,GridLayout的高度会被默认规则限制。 - 错误的size设置:
size: (root.width, root.height)把GridLayout的高度固定成和ScrollView一样,就算子控件总高度超过ScrollView,GridLayout也不会被撑开,自然触发不了滚动。
修改后的GridLayout代码如下:
GridLayout: size_hint_x: None size_hint_y: None # 修正大小写错误 width: root.width # 明确宽度,适配ScrollView cols: 2 height: self.minimum_height row_default_height: 150 row_force_default: True
关键修改说明
- 把
size_hint_Y改成size_hint_y,让Kivy正确识别这个属性,取消高度的自动适配。 - 删除
size: (root.width, root.height),让GridLayout的高度由self.minimum_height决定,当子控件总高度超过ScrollView时,布局会被撑开,滚动功能就能正常工作。 - 添加
width: root.width,因为size_hint_x: None需要明确宽度,保证GridLayout和ScrollView同宽,避免布局错位。
内容的提问来源于stack exchange,提问作者user18315433
相关产品推荐
相关产品推荐

