关于python:ScrollView小部件无法在kivy中倾斜

ScrollView widget not scolling in kivy

我在使用ScollView窗口小部件时遇到一些问题,试图使动态生成的标签堆栈可滚动。 我可能会误解应该使用ScrollView的方式,所以我希望有人可以为我澄清一下。 下面的代码从csv中读取一堆数据,并且在显示该代码时,如果有很多数据,该程序基本上将尝试将所有文本/标签压缩到GridLayout中。 我希望数据可以滚动。 这是代码的抽象版本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class showData(Screen):
def __init__(self, **kwargs):
    super(showData, self).__init__(**kwargs)

    self.my_data = read_csv_to_dict()
    self.data_exists = 0 if len(self.my_data) == 0 else 1

    ### Create Widgets ###      
    layout_main = BoxLayout(orientation = 'vertical')
    layout_back_button = BoxLayout(padding = [0, 0, 0, 20])
    self.layout_data = GridLayout(cols = 3 if self.data_exists else 1)  
    self.scrollview_data = ScrollView()

    button_back = Button(text = 'Main menu')

    ### Add widgets ###
    self.add_widget(layout_main)
    layout_main.add_widget(layout_back_button)
    layout_main.add_widget(self.scrollview_data)

    layout_back_button.add_widget(button_back)

    if self.data_exists:
        self.layout_data.add_widget(Label(text = 'label 1'))
        self.layout_data.add_widget(Label(text = 'label 2'))
        self.layout_data.add_widget(Label(text = 'label 3'))
        self.display_data(self)
        self.scrollview_data.add_widget(self.layout_data)
    else:
        self.scrollview_data.add_widget(Label(text = 'Records are empty'))

    ### Create button bindings ###
    button_back.bind(on_press = switch_screen_to_main)      

def display_data(obj, self):

    data_dictReader = read_csv_to_dictReader()

    for data_row in data_dictReader:
        for value in data_row.values():
            self.layout_data.add_widget( Label( text = value))

GridLayout /数据不可滚动。 有人可以告诉我如何修复上面的代码以使其可滚动吗? 谢谢。


您在GridLayout的Kivy文档中缺少一些内容。 它们是确保GridLayout"足够大以进行滚动"所必需的:

  • 您必须确保将size_hint_y设置为None,因为默认1在这种情况下不方便
  • GridLayoutminimum_height绑定到layout.setter('height')
  • 确保ScrollView的大小适合滚动
  • 这个例子几乎可以在文档中找到:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    from kivy.app import App
    from kivy.uix.scrollview import ScrollView
    from kivy.uix.gridlayout import GridLayout
    from kivy.uix.button import Button

    class Example(App):

        def build(self):
            layout = GridLayout(cols=1, spacing=10, size_hint_y=None)
            # Make sure the height is such that there is something to scroll.
            layout.bind(minimum_height=layout.setter('height'))
            for i in range(30):
                btn = Button(text=str(i), size_hint_y=None, height=40)
                layout.add_widget(btn)
            root = ScrollView()
            root.add_widget(layout)
            return root

    if __name__ == '__main__':
        Example().run()

    在此示例中,ScrollViewWindow的大小,但是您可以使用size_hintsize属性对其进行操作。