我在使用ScollView Widget时遇到了一些问题,试图让动态生成的标签堆栈可滚动。我可能误解了ScrollView的使用方式,所以我希望有人可以为我澄清一下。下面的代码从csv读取一堆数据,当显示该代码时,如果有大量数据,程序将基本上尝试将所有文本/标签压缩到GridLayout中。我希望数据可滚动。这是代码的抽象版本:
class showData(Screen):
def __init__(self, **kwargs):
super(showData, self).__init__(**kwargs)
self.my_data = read_csv_to_dict()
self.data_exists = 0 if len(self.my_data) == 0 else 1
### Create Widgets ###
layout_main = BoxLayout(orientation = 'vertical')
layout_back_button = BoxLayout(padding = [0, 0, 0, 20])
self.layout_data = GridLayout(cols = 3 if self.data_exists else 1)
self.scrollview_data = ScrollView()
button_back = Button(text = 'Main menu')
### Add widgets ###
self.add_widget(layout_main)
layout_main.add_widget(layout_back_button)
layout_main.add_widget(self.scrollview_data)
layout_back_button.add_widget(button_back)
if self.data_exists:
self.layout_data.add_widget(Label(text = 'label 1'))
self.layout_data.add_widget(Label(text = 'label 2'))
self.layout_data.add_widget(Label(text = 'label 3'))
self.display_data(self)
self.scrollview_data.add_widget(self.layout_data)
else:
self.scrollview_data.add_widget(Label(text = 'Records are empty'))
### Create button bindings ###
button_back.bind(on_press = switch_screen_to_main)
def display_data(obj, self):
data_dictReader = read_csv_to_dictReader()
for data_row in data_dictReader:
for value in data_row.values():
self.layout_data.add_widget( Label( text = value))
GridLayout / data不可滚动。有人能告诉我如何修复上面的代码使其可滚动?谢谢。
答案 0 :(得分:8)
您的GridLayout上缺少a few things from the Kivy Documentation。它们是确保GridLayout“足够大以滚动”所必需的:
size_hint_y
设置为None
,因为在这种情况下默认1
不方便minimum_height
的{{1}}绑定到GridLayout
。layout.setter('height')
的大小适合滚动这个例子几乎就是你在文档中找到的:
ScrollView
在此示例中,from kivy.app import App
from kivy.uix.scrollview import ScrollView
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
class Example(App):
def build(self):
layout = GridLayout(cols=1, spacing=10, size_hint_y=None)
# Make sure the height is such that there is something to scroll.
layout.bind(minimum_height=layout.setter('height'))
for i in range(30):
btn = Button(text=str(i), size_hint_y=None, height=40)
layout.add_widget(btn)
root = ScrollView()
root.add_widget(layout)
return root
if __name__ == '__main__':
Example().run()
是ScrollView
的大小,但您可以使用Window
和size_hint
属性对其进行操作。