2017-07-17 56 views
1

我想在我的kivy應用程序,並在我的知識kivy添加刷卡事件沒有如on_touch_lefton_touch_right可用的事件,但它有另一個on_touch_move功能,我認爲可以用於此目的如何在python kivy應用程序中左右滑動?

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

我在上面的代碼中注意到的是,如果我們向右滑動touch.x值增加,並且如果我們向右滑動touch.x值減少。我們只需將第一個和最後一個touch.x值之間的差異用於預測左/右滑動。

問題是如何存儲和檢索從初始值到最終值的touch.x值。

+1

我覺得這個[問題](https://stackoverflow.com/questions/30934445/kivy-swiping-carousel-screenmanager)是類似的,可以幫助你。 – KelvinS

+0

接受的答案必須導入手勢模塊,我不喜歡這樣。 – Eka

回答

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 > some-value設定最低刷卡範圍做比較一些行動。

+0

這是一個很棒的答案,我沒有想到,謝謝。因爲我在一個類中使用了這個函數,所以'initial'有一個小問題,它必須是函數內部的'self.initial'。我也採取了你的最後建議,我作爲百分比,而不是差異,它的作品令人驚歎 – Eka

+0

是的,我錯過了'self.initial'部分,但我很高興它的工作:) –

1

我用on_touch_downtouch.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"