【问题标题】:kivy scrollview gets stuckkivy 滚动视图卡住了
【发布时间】:2020-05-26 00:33:30
【问题描述】:

我的 Kivy 应用中有一个滚动视图对象。滚动视图包含一个 boxlayout,其中包含一定数量的图像。在运行时,更多的图像被添加到这个 boxlayout 中。目前,我尝试通过更改 scroll_y 属性来调整滚动视图以适应更改,并且效果很好。在某些时候它卡住了(大约在第 225 张图像上),我不知道如何解决这个问题。如果更改,Kivy 是否有办法自动重新调整滚动视图?还是有比我做的更好的方法来解决这个问题?

这就是我迄今为止在 python 中所做的事情(在滚动视图类中):

   def on_scroll_y(self, instance, scroll_val):
        global main_screen, generate_id
        if scroll_val < get_scroll_distance() * scrolls_to_another_page:
            box = main_screen.ids.notebook_image # this is the boxlayout that holds the images
            new_image = MyImage() # just an image class
            new_image.id = next(generate_id)
            box.add_widget(new_image)
            self.scroll_y = new_image.height / box.height # this is my try to adjust the scroll value

在kv文件中是这样定义的:

           MyScrollView:
                bar_color: [1, 0, 0, 1]
                id: notebook_scroll
                padding: 0
                spacing: 0
                do_scroll: (False, True)  # up and down
                BoxLayout:
                    padding: 0
                    spacing: 0
                    orientation: 'vertical'
                    id: notebook_image
                    size_hint: 1, None
                    height: self.minimum_height
                    MyImage:

<MyImage>:
    source: 'images/notebook2.png'
    allow_stretch: True
    keep_ratio: False
    size: root.get_size_for_notebook() #not important for this case, just screen size manipulation
    size_hint: None, None

【问题讨论】:

    标签: python kivy kivy-language


    【解决方案1】:

    当我回答你关于这个主题的原始问题时,我使用了测试:

     if scroll_val < 0.05:
    

    但是,我认为这是一个糟糕的选择。我的测试(以及你的测试)的问题在于,随着box.height 变大(添加了Images),计算出的新scroll_y 变得越来越小。一旦新的scroll_y 小于测试值(在我的情况下为0.05 或在您的情况下为get_scroll_distance() * scrolls_to_another_page),然后设置新的scroll_y 值将再次触发on_scroll_y() 方法。这可能导致无限循环。我认为最好的选择是实际测试与0.0 的相等性。在我所有的计算机科学生涯中,我一直避免测试浮点值的相等性,但我相信这是一个例外。因此,我建议将您的测试更改为:

     if scroll_val == 0.0:
    

    【讨论】:

    • 谢谢,但它只是卡住了哈哈。但是,我想我知道什么可以解决这个问题。每当我将另一个图像添加到 boxlayout 时,它都会“出现故障”或“反弹”,因为 scroll_y 值设置不正确。我尝试这样做: self.scroll_y = self.scroll_y * box.height / old_height (我试图让它处于相同的位置,所以随着高度的变化没有任何移动)。不幸的是,这个公式并没有真正起作用。如果您对更好的公式有任何想法,我想我可以从那里得到它:)
    • 试试self.scroll_y = new_image.height / (box.height + new_image.height)
    猜你喜欢
    • 1970-01-01
    • 2017-10-20
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多