【问题标题】:How to swipe left and right in python kivy app?如何在 python kivy 应用程序中左右滑动?
【发布时间】:2017-07-17 12:23:00
【问题描述】:

我想在我的 kivy 应用程序中添加一个滑动事件,据我所知,kivy 没有可用的事件,例如 on_touch_lefton_touch_right,但它有另一个 on_touch_move 函数,我认为可以用于此目的

class TestWidget(BoxLayout):
    def on_touch_move(self, touch):
        print touch.x

我在上面的代码中注意到的是,如果我们向右滑动touch.x 值会增加,如果我们向右滑动touch.x 值会减少。我们只需要获取第一个和最后一个 touch.x 值之间的差异来预测左/右滑动。

问题是如何存储和检索从初始到最终的touch.x 值。

【问题讨论】:

  • 我觉得这个question 很相似,可能对你有帮助。
  • 接受的答案必须导入手势模块,我不喜欢那样做。

标签: python kivy


【解决方案1】:

除了使用on_touch_move事件,你可以使用on_touch_down并保存touch.x,然后使用on_touch_up并比较touch.x,例如:

initial = 0
def on_touch_down(self, touch):
    initial = touch.x

def on_touch_up(self, touch):
    if touch.x > initial:
        # do something
    elif touch.x < initial:
        # do other thing
    else: 
        # what happens if there is no move

更好的方法是使用if touch.x - initial &gt; some-value 进行比较以设置最小滑动范围以执行某些操作。

【讨论】:

  • 这是一个很棒的答案,我没想到,谢谢。因为我在一个类中使用它,所以 initial 有一个小问题,它必须是 self.initial 内部函数。我也采纳了你的最后建议,我将其设为百分比而不是差异,效果惊人
  • 是的,我错过了 self.initial 部分,但我很高兴它成功了 :)
【解决方案2】:

我使用 on_touch_down 以及 touch.dxtouch.dy 属性来计算它。原因是我需要动态计算滑动的长度,因为它决定了图像的 alpha。对于非动态计算,我发现 Moe A 的解决方案更直接且资源消耗更少。

    def on_touch_move(self, touch):
        if self.enabled:
            self.x_total += touch.dx
            self.y_total += touch.dy

            if abs(self.x_total) > abs(self.y_total):
                "do something"
            else:
                "do something else"

【讨论】:

    【解决方案3】:
    def on_touch_move(self,touch):
        if touch.dx > 0:
            self.ids.scrn_mnger.transition.direction = 'right'
            self.ids.scrn_mnger.current = 'scrn_open'
        elif touch.dx < 0:
            self.ids.scrn_mnger.transition.direction = 'left'
            self.ids.scrn_mnger.current = 'scrn_media'
    

    【讨论】:

    • 请考虑将 cmets 添加到您的答案中,以帮助 OP 和其他人了解它如何解决 OP 的问题。
    猜你喜欢
    • 1970-01-01
    • 2013-11-24
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 1970-01-01
    相关资源
    最近更新 更多