如何在Kivy中触发一次过卷动作?

2024-09-22 16:41:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个ScrollView,当你过度滚动到顶部时,它应该有一个更新功能(就像在许多应用程序中一样)。我已经找到了一种方法,当超卷超过某个阈值时触发它,但它会触发很多次,因为每次移动都会触发on_overscroll事件。那么有没有办法限制它呢?
我的代码如下:

from kivy.app import App
from kivy.uix.scrollview import ScrollView
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button

from kivy.effects.dampedscroll import DampedScrollEffect

class Effect(DampedScrollEffect):
    def on_overscroll(self, *args):
        super().on_overscroll(*args)
        if self.overscroll < -50:
            print('hey')

class TestApp(App):
    def build(self):
        sv = ScrollView(effect_cls = Effect,
                        size_hint_y = 0.2)

        gl = GridLayout(cols = 1,
                        size_hint_y = None)
        gl.bind(minimum_height = gl.setter('height'))

        for i in range(5):
            gl.add_widget(Button(text = str(i),
                                 size_hint = (None, None)))

        sv.add_widget(gl)

        return sv

TestApp().run()

所以,正如你所看到的,当溢出超过50时,它会打印一条简单的消息。但当你真正尝试时,你会发现它打印了很多次。我想要的是触发一个事件,在一段时间内保持不可迁移(比如一秒钟),并更新内容。我尝试过搞乱布尔标志和Clock,但是没有用。在这里能做什么?在


Tags: fromimportselfnoneappsizeon事件
1条回答
网友
1楼 · 发布于 2024-09-22 16:41:36

我会在这里使用一个有状态的装饰器:

class call_control:

    def __init__(self, max_call_interval):
        self._max_call_interval = max_call_interval
        self._last_call = time()

    def __call__(self, function):

        def wrapped(*args, **kwargs):
            now = time()

            if now - self._last_call > self._max_call_interval:
                self._last_call = now

                function(*args, **kwargs)

        return wrapped


class Effect(DampedScrollEffect):

    def on_overscroll(self, *args):
        super().on_overscroll(*args)

        if self.overscroll < -50:
            self.do_something()

    @call_control(max_call_interval=1)
    def do_something(self):
        print('hey')

相关问题 更多 >