尝试根据文档中给出的示例,弄清楚如何使用KV语言实现直接的ScrollView。我无法相信我找不到这个例子(只有部分解决方案),所以我认为这很容易。事实证明并非如此。
我的问题是我需要使用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()
更新:更正了以下脚本。
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()
答案 0 :(得分:0)
Kivy首先打电话给Widget.__init__()
非常挑剔。因此,如果您覆盖小部件的__init__
,请务必先调用super().__init__
,否则您可能会遇到遇到的错误或“随机”崩溃。
修复变更
class MainScreen(FloatLayout):
def __init__(self, **kwargs):
self.buildList()
super(MainScreen, self).__init__(**kwargs)
到
class MainScreen(FloatLayout):
def __init__(self, **kwargs):
super(MainScreen, self).__init__(**kwargs)
self.buildList()