2017-09-15 118 views
0

我正在尝试使用垂直BoxLayout动态地构建Kivy布局,其中包含可在运行时更改的自定义小部件MyRowlayout example 每一行都是一个水平的BoxLayoutKivy嵌套BoxLayout堆栈左下角的小部件

我不使用网格布局,因为 MyRow布局正在开发,可以在不久的将来将小工具等等类似这样的例子 layout example 2

但随着更改代码

下面我只会看到窗口左下角堆叠在一起的小部件。

from kivy.app import App 
from kivy.uix.widget import Widget 
from kivy.uix.boxlayout import BoxLayout 
from kivy.properties import StringProperty 

class MyRow(Widget): 
    a = StringProperty('a') 
    b = StringProperty('b') 

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

class MainScreen(Widget): 

    rows = [['a1','b1'],['a2','b2']] #example data 

    mainLayout = BoxLayout(orientation='vertical', spacing=5) 

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

     self.add_widget(self.mainLayout) 

     for r in self.rows: 
      row_widget = MyRow() 

      row_widget.a = r[0] 
      row_widget.b = r[1] 

      self.mainLayout.add_widget(row_widget) 

class MyApp(App): 

    def build(self): 
     return MainScreen() 

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

,这是千伏文件:

<MyRow> 
    BoxLayout: 
     orientation: "horizontal" 
     spacing: 30 
     Label: 
      id: a_label 
      text: root.a 
     Label: 
      id: b_label 
      text: root.b 

回答

1

在您的草图,它说MyRow是基于水平的BoxLayout。但事实并非如此。它是建立在widget

简单地改变

class MyRow(Widget): 

class MyRow(BoxLayout): 

将解决你的问题。

enter image description here


为了获得间隔的权利或更好,我会更新你的代码下面

from kivy.app import App 
from kivy.uix.widget import Widget 
from kivy.uix.boxlayout import BoxLayout 
from kivy.properties import StringProperty 
from kivy.base import Builder 



class MyRow(BoxLayout): 
    a = StringProperty('a') 
    b = StringProperty('b') 

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

class MainScreen(BoxLayout): 

    rows = [['a1','b1'],['a2','b2']]*5 

    def __init__(self, **kwargs): 
     super(MainScreen, self).__init__(**kwargs) 
     self.orientation = "vertical" 

     for r in self.rows: 
      row_widget = MyRow() 

      row_widget.a = r[0] 
      row_widget.b = r[1] 

      self.add_widget(row_widget) 



class MyApp(App): 

    def build(self): 
     return MainScreen() 

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

和你千伏

<MyRow>: 
    orientation: "horizontal" 
    spacing: 30 
    Label: 
     id: a_label 
     text: root.a 
    Label: 
     id: b_label 
     text: root.b 

,让你enter image description here


要从Boxlayot在KV文件使用<[email protected]>:

+0

Python中使用class Row(BoxLayout):继承这个回答你的问题?如果考虑接受,或者它只是帮助了你,你可能会考虑采取行动。 – PalimPalim