gpt4 book ai didi

python - 如何动态添加项目到kivy中的 ScrollView

转载 作者:太空宇宙 更新时间:2023-11-03 21:10:01 24 4
gpt4 key购买 nike

你好,我对 kivy 比较陌生。到目前为止,做基本的事情相对简单,但这却难倒了我。我正在制作一个应用程序,需要将矩形 Canvas 项目动态添加到 ScrollView 中的网格中。因为我这样做,所以我需要在 python 中而不是在 .kv 文件中创建 ScrollView 。我怎样才能做到这一点,以便在调整窗口大小时矩形的大小与窗口大小相同?

.py 文件:

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.relativelayout import RelativeLayout
from kivy.graphics import Line,Rectangle
from kivy.uix.carousel import Carousel
from kivy.uix.scrollview import ScrollView
from kivy.core.window import Window

class Scroll(ScrollView):
def __init__(self, **kwargs):
super(Scroll, self).__init__(**kwargs)
layout = GridLayout(cols=1, spacing=10, size_hint_y=None)
layout.bind(minimum_height=layout.setter('height'))
# Make sure the height is such that there is something to scroll.
for i in range(100):
SkillStat = RelativeLayout(pos=(0,0), height=100, size_hint_y=None, size_hint_x=self.width)
with SkillStat.canvas:
Rectangle(pos=self.pos,size=(self.width, 90))
layout.add_widget(SkillStat)

self.add_widget(layout)
pass
pass
class Sheet(Carousel):
pass

class SheetApp(App):
def build(self):
return Sheet()

if __name__ == '__main__':
SheetApp().run()

.kv 文件:

# file name: Sheet.kv

<Sheet>:
RelativeLayout:
Scroll:
size_hint:(1,1)

最佳答案

代码中的两个主要问题是:

  1. 您正在对SkillStat进行所有尺寸和位置设置。及其 Canvas __init__()方法。在 __init__()控件的位置始终为 (0,0),大小为 (100, 100)。在实际绘制小部件之前,这些属性不会设置为实际值。
  2. 您正在 python 而不是 kv 中完成所有这些操作。在 kv ,为您设置的许多属性创建绑定(bind),并自动更新。如果您在 python 中进行小部件设置,则必须自己提供这些绑定(bind)。

这是您的 Scroll 的修改版本类和新MyRelativeLayout处理这些绑定(bind)的类:

class MyRelativeLayout(RelativeLayout):
def adjust_size(self, *args):
self.rect.size = self.size # set the size of the Rectangle


class Scroll(ScrollView):
def __init__(self, **kwargs):
super(Scroll, self).__init__(**kwargs)
layout = GridLayout(cols=1, spacing=10, size_hint_y=None)
layout.bind(minimum_height=layout.setter('height'))
# Make sure the height is such that there is something to scroll.
for i in range(100):
SkillStat = MyRelativeLayout(pos=(0,0), height=100, size_hint=(1.0, None))
with SkillStat.canvas.before:
SkillStat.rect = Rectangle()
SkillStat.bind(size=SkillStat.adjust_size)
layout.add_widget(SkillStat)
self.add_widget(layout)

注意 SkillStat.bind()调用以创建所需的绑定(bind),以及 Rectangle另存为SkillStat.rect在每个 MyRelativeLayout实例。这些绑定(bind)将在 SkillStat 后立即触发。显示,因此初始 possize Rectangle的不需要。

编辑:设置 pos Rectangle的绑定(bind)中可能会引起问题。默认pos Rectangle的是 (0,0) ,这应该始终是这样。所以,我们只需要调整size Rectangle的。我已删除 pos 的绑定(bind).

关于python - 如何动态添加项目到kivy中的 ScrollView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55133191/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com