Kivy重复行动

时间:2015-06-01 20:55:34

标签: python kivy

我一直在玩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)

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

在运动事件方面,我有什么遗漏吗?

1 个答案:

答案 0 :(得分:3)

每次调用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

确保您只在碰撞检查中返回True,否则您可能会在不想要的时候取消触摸事件。请注意,这仅适用于触摸事件on_touch_down / on_touch_move / on_touch_upButtonBehavior事件on_presson_releaseButton小部件上的事件一样,会执行碰撞检查。