为什么我的 Kivy ScrollView 无法滚动?

Why is scrolling with my Kivy ScrollView not working?

我正在尝试在 GridLayout 中滚动,我在其中为不同的电影名称创建了标签。

我遵循了 Kivy 文档并将标签的 size_hints 之一设置为 None。当我尝试滚动时没有任何反应,滚动条也没有出现。

import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.scrollview import ScrollView
from kivy.uix.gridlayout import GridLayout


class Grid(GridLayout):
    def __init__(self, **kwargs):
        super(Grid, self).__init__(**kwargs)
        movies = [
            "It Happened One Night", 
            "Citizen Kane", 
            "All About Eve", 
            "The Irishman", 
            "Singin' in the Rain", 
            "Double Indemnity", 
            "L.A. Confidential"
        ]
        
        self.rows = len(movies)
        # Iterate over list and add labels
        for i in movies:
            self.add_widget(Label(text=i, size_hint_y=None, font_size=50))


class ScrollableView(ScrollView):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.do_scroll_x = False
        self.do_scroll_y = True
        self.size_hint_min = (0.5, 0.5)
        self.add_widget(Grid())


class MyApp(App):
    def build(self):
        return ScrollableView()


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

size_hint_y = NoneScrollView 的 child 所必需的,但您将其分配给 child 的 child。然后就可以把Gridheight绑定到minimum_height属性了。此外,使用 minimum_height 作为 Grid 要求 Grid 的 children 已明确定义 heights。这是您的代码的修改版本:

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.scrollview import ScrollView
from kivy.uix.gridlayout import GridLayout


class Grid(GridLayout):
    def __init__(self, **kwargs):
        super(Grid, self).__init__(**kwargs)
        self.size_hint_y = None
        movies = [
            "It Happened One Night",
            "Citizen Kane",
            "All About Eve",
            "The Irishman",
            "Singin' in the Rain",
            "Double Indemnity",
            "L.A. Confidential"
        ]

        self.bind(minimum_height=self.setter('height'))  # this insures that the height of the Grid can contain all the children

        self.rows = len(movies)
        # Iterate over list and add labels
        for i in movies:
            self.add_widget(Label(text=i, size_hint_y=None, height=100, font_size=50))  # note height setting

class ScrollableView(ScrollView):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.do_scroll_x = False
        self.do_scroll_y = True
        self.size_hint_min = (0.5, 0.5)
        self.add_widget(Grid())


class MyApp(App):
    def build(self):
        return ScrollableView()


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