Kivy 重复动作

Kivy Repeating Actions

我一直在研究 kivy 的触摸输入,但是我注意到尽管按钮只被按下一次,但我的函数被调用了多次。

def on_touch_down(self,touch):
    with self.canvas:
        if self.clearcanvas:
            self.canvas.clear()
        Color(*self.color)
        touch.ud['line'] = Line(points=(touch.x, touch.y),width =3)
    self.actions()
    return True


def on_touch_move(self, touch):
    if self.clearcanvas:
        touch.ud['line'].points += [touch.x, touch.y]
        self.linecoord = touch.ud['line'].points


def on_touch_up(self, touch):
    pass


def actions(self):
    #if shape is accepted by user
    if self.clearcanvas:
        def acceptshape(obj):


            # test to see if shape overlaps
            self.linecoordtuple = []
            for i in range(0,len(self.linecoord)-1,2):
                x = round(self.linecoord[i])
                y = round(self.linecoord[i+1])
                self.linecoordtuple.append((x,y))
            crossingcheck = len(self.linecoordtuple)==len(set(self.linecoordtuple))


            # if no overlap and a shape is drawn, plots mesh
            if self.convexsmoothing:
                if len(self.linecoord)>0:
                    self.clearcanvas = False
                    with self.canvas:
                        self.canvas.clear()
                        Color(*self.color)
                        self.build_mesh()
                else:
                    print "Invalid Shape"
                    self.canvas.clear()
                    self.clearcanvas = True
            else:
                if len(self.linecoord)>0 and crossingcheck:
                    self.clearcanvas = False
                    with self.canvas:
                        self.canvas.clear()
                        Color(*self.color)
                        self.build_mesh()
                else:
                    print "Invalid Shape"
                    self.canvas.clear()
                    self.clearcanvas = True

        keepbtn.bind(on_press=acceptshape)

例如,当我按下接受按钮并且形状无效时,我收到重复消息: 无效形状 无效形状 无效形状 无效形状 形状无效

关于运动事件,我是否遗漏了什么?

每次调用 on_touch_down() 方法时,您都会创建一个全新的 acceptshape() 函数并将其绑定到按钮。因此,当您按下按钮时,它会为您之前每次触摸时调用一个单独的 acceptshape() 函数。您应该创建一个函数(或方法),并在首次创建小部件时将其绑定到按钮一次。

仅供参考 - Kivy 在发送触摸事件时不执行碰撞检查 - 由你来做这样的检查(或者不做,如果你想接收所有触摸事件)。你可以通过像这样用碰撞检查包装函数体来做到这一点:

def on_touch_down(self,touch):
    if self.collide_point(*touch.pos):
        with self.canvas:
            if self.clearcanvas:
                self.canvas.clear()
            Color(*self.color)
            touch.ud['line'] = Line(points=(touch.x, touch.y),width =3)
        self.actions()
        return True

确保您只 return True 在碰撞检查中,否则您可能会在无意中取消触摸事件。请注意,这仅适用于触摸事件,on_touch_down/on_touch_move/on_touch_upButtonBehavior 事件 on_presson_release,与 Button 小部件上的事件一样,执行碰撞检查。