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

PC端Kivy ScrollView配置:实现超出区域内容滚动可见

解决ScrollView内容初始隐藏需向下滚动查看的问题

要实现按钮位于布局原点下方、初始不可见需向下滚动查看的效果,你需要调整滚动内容布局的尺寸,并修改按钮的位置参数,具体步骤如下:

关键修改点

  1. 给滚动内容留出足够空间:原代码中RelativeLayout的size_hint_y=1,导致其高度和ScrollView完全一致,没有可滚动的额外空间。需要将size_hint_y设为None,并手动设置一个大于ScrollView高度的height值。
  2. 将按钮移至布局原点下方:把按钮的pos_hint中的y值设为负数,这样按钮就会位于布局左下角(原点)的下方区域,初始状态下不会在ScrollView的可见范围内。
  3. 确保ScrollView支持向下滚动:默认ScrollView的滚动范围会自动适配内容尺寸,只要内容高度大于ScrollView高度,就能触发滚动。

修改后的完整代码

from kivy.core.window import Window
from kivy.uix.widget import Widget
from kivy.graphics import Color, Rectangle
from kivy.uix.scrollview import ScrollView
from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.button import Button

class MyWidget(Widget):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        Window.size = (339, 600)
        self.w1 = self
        with self.w1.canvas.before:
            Color(0.941176, 0.941176, 0.941176, 1)
            self.rect = Rectangle(size=self.w1.size, pos=self.w1.pos)
        self.w1.bind(pos=self.update_rect, size=self.update_rect)
        
        # 保持ScrollView的设置不变
        self.scroll1 = ScrollView(size_hint=(None, 1), size=(Window.width, Window.height), scroll_type=['bars', "content"])
        self.w1.add_widget(self.scroll1)
        
        # 修改布局:设置固定高度(大于ScrollView高度),开启滚动空间
        self.scroll1_layout = RelativeLayout(pos_hint={'x':0.0, 'y':0.0}, size_hint=(0.626844, None))
        self.scroll1_layout.height = Window.height * 2  # 布局高度设为窗口高度的2倍,留出滚动空间
        self.scroll1.add_widget(self.scroll1_layout)
        
        # 按钮1:y设为负数,位于原点下方
        self.button1 = Button(text="Button", pos_hint={'x':0.568182, 'y':-0.2}, size_hint=(1.30682, 0.0545617))
        self.scroll1_layout.add_widget(self.button1)
        
        # 按钮2:y设为更小的负数,位置更靠下
        self.button2 = Button(text="Button", pos_hint={'x':0.227273, 'y':-0.5}, size_hint=(0.909091, 0.0992844))
        self.scroll1_layout.add_widget(self.button2)
    
    def update_rect(self, *args):
        self.rect.pos = self.w1.pos
        self.rect.size = self.w1.size

说明

  • 调整scroll1_layout.height的数值可以控制滚动区域的大小,数值越大可滚动的范围越广。
  • 按钮的y值负数越小,位置越靠下,需要滚动的距离就越长。你可以根据需求调整具体数值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 13:10:25