python - 如何在 Kivy 中使用 ScrollView?
问题描述
我想在屏幕的特定部分创建滚动视图。
视图中的内容数量可以改变 - 因此我想通过 for 循环将小部件插入视图。
这就是
我在这个问题上挣扎了一段时间的观点。我似乎无法:
- 使用 for 循环将小部件插入视图
- 将视图放置在特定位置。
`
class PlaylistWidget(ScrollView):
def __init__(self, **kwargs):
super(PlaylistWidget, self).__init__(**kwargs)
self.bar_width = 50
self.size_hint = 1, .1
self.scroll_type = ['bars']
self.bar_inactive_color = 5, 20, 10, .5
self.bar_color = 5, 10, 15, .8
self.do_scroll_x = False
self.do_scroll_y = True
grid = GridLayout()
grid.height = self.size[1]
grid.size_hint_y = None
grid.cols = 1
grid.row_default_height = '20dp'
grid.row_force_default = True
for i in range(148):
a = Label()
a.text = "Blah blah blah"
a.font_size = 30
a.size_hint_y = None
a.size_hint_x = 1.0
a.height = self.size[1]
grid.add_widget(a)
self.add_widget(grid)
`这是我做的一个尝试代码......
谢谢。
奥菲克·哈雷尔。
解决方案
我认为你所缺少的是你必须设置每个Label
添加到的GridLayout
高度,并且你还必须设置的高度GridLayout
。这是执行此操作的代码的修改版本:
class PlaylistWidget(ScrollView):
def __init__(self, **kwargs):
super(PlaylistWidget, self).__init__(**kwargs)
self.bar_width = 50
self.size_hint = 1, .1
self.scroll_type = ['bars']
self.bar_inactive_color = 5, 20, 10, .5
self.bar_color = 5, 10, 15, .8
self.do_scroll_x = False
self.do_scroll_y = True
grid = GridLayout()
# star with zero height
grid.height = 0
grid.size_hint_y = None
grid.cols = 1
grid.row_default_height = '20dp'
grid.row_force_default = True
for i in range(148):
a = Label()
a.text = "Blah blah blah"
a.font_size = 30
a.size_hint_y = None
a.size_hint_x = 1.0
# set label height
a.height = grid.row_default_height
# increment grid height
grid.height += a.height
grid.add_widget(a)
self.add_widget(grid)
另一种方法是使用 kivy 语言设置ScrollView
. 这种方法利用minimum_height
了GridLayout
计算的优势,因此您不必计算height
的GridLayout
:
class PlaylistWidget(ScrollView):
def add_labels(self, *args):
grid = self.ids.grid
for i in range(148):
a = Label()
a.text = "Blah blah blah"
a.font_size = 30
a.size_hint_y = None
a.size_hint_x = 1.0
# set label height
a.height = grid.row_default_height
grid.add_widget(a)
kv = '''
PlaylistWidget:
bar_width: 50
size_hint: 1, .1
scroll_type: ['bars']
bar_inactive_color: 5, 20, 10, .5
bar_color: 5, 10, 15, .8
do_scroll_x: False
do_scroll_y: True
GridLayout:
id: grid
cols: 1
row_default_height: '20dp'
row_force_default: True
size_hint_y: None
height: self.minimum_height
'''
class TestApp(App):
def build(self):
pl = Builder.load_string(kv)
Clock.schedule_once(pl.add_labels)
return pl
TestApp().run()
推荐阅读
- reactjs - html 中的 Jest 覆盖率报告缺少覆盖率值
- python - pynput 键盘侦听器导致延迟
- python - 从头开始创建二级/内部索引
- apache-flink - Flink ParquetAvroWriters 给出演员表错误
- flutter - 我正在尝试 moor(sqflite builder),我正在关注文档但对我不起作用,如果有人实施,请提供帮助
- r - 如何将多个值从 URL 传递到 r 闪亮的复选框输入
- c# - Xamarin 中的自动滚动设置为计时器
- typescript - 如何在Typescript中将字符串映射到具有字符串值的已知枚举?
- machine-learning - 即使状态相同,深度强化学习模型也会采取不同的行动
- javascript - 如何从javascript中的二维数组获取价格数据?