如何使用 Kivy 在 ScrollView 中初始化 for 循环?

How can I initialize a for loop inside ScrollView with Kivy?

我是 Kivy 的新手,我正在尝试弄清楚如何使用 ScrollView。我想知道如何初始化 ScrollViewfor 循环内生成的按钮。到目前为止,这是我的代码:

main.py

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button


class My_list(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.orientation = "vertical"
        for i in range(10):
            b = Button(text=str(i))
            self.add_widget(b)

class MyBoxLayout(BoxLayout):
    pass

class MyApp(App):
    pass

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

my.kv

MyBoxLayout:

<MyBoxLayout>:
    orientation: "vertical"

#    ScrollView:
#        size_hint: 1, None
#        height: 200

    My_list:

    BoxLayout:
        size_hint: 1, .1
        TextInput:
        TextInput:

    Button:
        text: "Add Button"
        size_hint: 1, .1

这看起来很符合我的要求,但如果屏幕上显示的太多,我想用滚动条移动数字按钮。滚动条不应影响输入小部件和 Add Button.

我在 my.kv 中试过这个:

ScrollView:
    size_hint: 1, None
    height: 200

    My_list: 

但这似乎把整个布局搞乱了。有没有办法在 .kv 文件中使用 for 循环?或者还有什么其他方法可以使这项工作正常进行?

根据 Kivy 文档,

You must carefully specify the size of your content to get the desired scroll/pan effect. By default, the size_hint is (1, 1), so the content size will fit your ScrollView exactly (you will have nothing to scroll). You must deactivate at least one of the size_hint instructions (x or y) of the child to enable scrolling. Setting size_hint_min to not be None will also enable scrolling for that dimension when the ScrollView is smaller than the minimum size.

所以你需要的改变,在my.kv

    ScrollView:
#        size_hint: 1, None # Generally you don't need this.
#        height: 200 # Neither this.
        
        My_list:
            size_hint_y: None # Let the container expand vertically.
            height: self.minimum_height # Or, you can specify any other value.

并在 My_list

        b = Button(
                text=str(i),
                size_hint_y = None, # To set custom value.
                height = dp(100), # Specify height of the widget explicitly.
            )
        self.add_widget(b)