Skip to main content
 首页 » 编程设计

python之ScrollView 和触摸事件不能在 kivy 中协同工作

2025年02月15日8insus

我有一个屏幕,其中有可滚动的框布局。它工作正常,我可以滚动浏览屏幕内的标签、文本输入和按钮

 #kvfile 
<FirstScreen>: 
    ScrollView: 
        BoxLayout: 
            orientation:"vertical" 
            size_hint_y: None  
            height: self.minimum_height   
            #here some scrollable labels, text inputs, and buttons 
 
#python file 
class FirstScreen(Screen): 
    ''' 
    initial = 0 
    def on_touch_down(self, touch): 
        self.initial = touch.x 
 
    def on_touch_up(self, touch): 
        if touch.x > self.initial: 
            # do something 
        elif touch.x < self.initial: 
            # do other thing 
        else:  
            # what happens if there is no move 
    ''' 
    pass 

但是当我添加一个触摸事件来检测左右滑动时,滚动将被禁用。现在我可以左右滑动但不能滚动。如何同时启用滚动和滑动?

请您参考如下方法:

您正在打扰 event bubbling使用此代码,根本不会调用布局子项的 on_touch_down 方法。通常,您应该始终返回 True 或传递事件(或两者的某种组合)。

class FirstScreen(Screen): 
    initial = 0 
    def on_touch_down(self, touch): 
        self.initial = touch.x 
        return super(Screen, self).on_touch_down(touch) #pass the touch on 
 
    def on_touch_up(self, touch): 
        if touch.x > self.initial: 
            print "left" 
            return True #don't pass the touch on 
        elif touch.x < self.initial: 
            print "right" 
            return True 
        else:  
            print "no" 
            return super(Screen, self).on_touch_up(touch)