0
試圖找出如何基於文檔中給出的示例實現KV語言的直接滾動視圖。我不敢相信我找不到這樣的一個例子(只有部分解決方案),所以我認爲這很容易。原來不是。Kivy滾動視圖KV語言 - ID未定義
我的問題是,我需要使用add_widget來填充我的可滾動網格佈局,其中包含來自kivy腳本內的標籤列表。這是因爲我添加了可變數量的標籤(儘管在下面的示例中這個數字是固定的,以使事情變得簡單)。然而,程序不會讓我這樣做,說我爲網格佈局對象定義的ID沒有定義。因此我無法將標籤添加到網格佈局。
NameError: name '_gridlayout' is not defined
任何幫助表示讚賞。謝謝
from kivy.app import App
from kivy.uix.scrollview import ScrollView
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
Builder.load_string('''
<MainScreen>:
AnchorLayout:
anchor_x: 'center'
anchor_y: 'top'
size_hint: 1, .2
Label:
text: "Random text"
AnchorLayout:
anchor_x: 'center'
anchor_y: 'bottom'
size_hint: 1, .8
ScrollView:
GridLayout:
id: _gridlayout
cols: 1
padding: 10
spacing: 10
size_hint_y: None
width: 500
''')
class MainScreen(FloatLayout):
def __init__(self, **kwargs):
self.buildList()
super(MainScreen, self).__init__(**kwargs)
def buildList(self):
for i in range(30):
btn = Label(text=str(i), size_hint_y=None, height=40)
_gridlayout.add_widget(btn) # <- ERROR
class SMApp(App):
def build(self):
return MainScreen()
if __name__ == '__main__':
SMApp().run()
UPDATE:更正了下面的腳本。
from kivy.app import App
from kivy.uix.scrollview import ScrollView
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
Builder.load_string('''
<MainScreen>:
AnchorLayout:
anchor_x: 'center'
anchor_y: 'top'
size_hint: 1, .2
Label:
text: "Random text"
AnchorLayout:
anchor_x: 'center'
anchor_y: 'bottom'
size_hint: 1, .8
ScrollView:
GridLayout:
id: _gridlayout
cols: 1
padding: 10
spacing: 10
size_hint_y: None
width: 500
''')
class MainScreen(FloatLayout):
def __init__(self, **kwargs):
super(MainScreen, self).__init__(**kwargs)
self.buildList()
def buildList(self):
for i in range(30):
btn = Label(text=str(i), size_hint_y=None, height=40)
self.ids._gridlayout.add_widget(btn)
self.ids._gridlayout.bind(minimum_height=self.ids._gridlayout.setter('height'))
class SMApp(App):
def build(self):
return MainScreen()
if __name__ == '__main__':
SMApp().run()
嗯...我想通了,我需要使用 「self.ids._grid_layout」。雖然(AttributeError:'super'對象沒有屬性'__getattr__'),但是我認爲該方法是正確的,但會使應用崩潰。 –
'__init__'首先嚐試超級調用('super([...]).__ init __(** kwargs)',也許在添加小部件之前,kivy小部件首先需要做一些魔術。下次請添加完整追蹤 – syntonym
是的,就是這樣,再加上缺少的綁定來啓用滾動。非常感謝。我會記住下次發佈完整的回溯,對此表示遺憾。 我會繼續並更新我的OP已修正的腳本 –