向滚动视图添加多个小部件

时间:2017-05-11 20:19:05

标签: python-3.x scrollview kivy

我正在尝试获取一个可滚动的小部件表。每一行都有不同的输入(这里由TextInput给出)但我有更多的行(12),而不是我有屏幕空间,所以我把它放在ScrollView中。

问题在于下面的代码我得到以下错误。

 kivy.uix.widget.WidgetException: Cannot add <kivy.uix.boxlayout.BoxLayout object at 0x10e0abf30>, it already has a parent <kivy.uix.floatlayout.FloatLayout object at 0x10e0abfa0>

我的猜测是因为你不能为布局添加多个小部件而不给它们所有唯一ID?我坚持为什么main.add_widget(row_layout)不允许你根据需要多次迭代?

.kv

ScrollView:
    do_scroll_x: False
        MyWidget:

我的小部件如下所示:

within .py

class MyWidget(BoxLayout):

def __init__(self, **kwargs):
    super(MyWidget, self).__init__(**kwargs)

    col1 = TextInput()
    col2 = TextInput()
    col3 = TextInput()
    col4 = TextInput()
    col5 = TextInput()
    col6 = TextInput()
    col7 = TextInput()
    col8 = TextInput()
    cols = [col1,col2,col3,col4,col5,col6,col7,col8]

    row_layout = BoxLayout(orientation='horizontal')
    print("Constructing row...")
    for col in cols:
        print col
        row_layout.add_widget(col)

    print("Iterating through rows...")
    main = FloatLayout(orientation='vertical')
    for row in range(12):
        print("adding...",row)
        main.add_widget(row_layout)

    self.add_widget(main)

1 个答案:

答案 0 :(得分:0)

经过一些进一步的修修补补,我把它解决了。您似乎需要为每一行创建一个新实例。

class MyWidget(BoxLayout):

def __init__(self, **kwargs):
    super(MyWidget, self).__init__(**kwargs)

    layout = GridLayout(cols=1,orientation='vertical',size_hint_y=None)

    layout.bind(minimum_height=layout.setter('height'))

    for row in range(24):
        col1 = TextInput()
        col2 = TextInput()
        col3 = TextInput()
        col4 = TextInput()
        col5 = TextInput()
        col6 = TextInput()
        col7 = TextInput()
        col8 = TextInput()
        cols = [col1,col2,col3,col4,col5,col6,col7,col8]
        row_layout = BoxLayout(orientation='horizontal', width=800,height=40,size_hint=(None, None))

        for col in cols:
            row_layout.add_widget(col)

        layout.add_widget(row_layout)

    root = ScrollView(do_scroll_x=False)
    root.add_widget(layout)
    self.add_widget(root)

相关的kivy条目只是:

.kv
MyWidget: