2017-09-15 43 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