kivy on_touch_up()触发不止一次?

时间:2019-05-17 06:48:26

标签: python kivy

我想知道,是否有一种方法可以使on_touch_up()在正确的情况下连续触发?输出如下:

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Color, Ellipse, Line


class MyPaintWidget(Widget):

    def on_touch_down(self, touch):
        with self.canvas:
            Color(1, 1, 0)
            touch.ud['line'] = Line(points=(touch.x, touch.y))
        print(touch.spos, "Down")

    def on_touch_move(self, touch):
        touch.ud['line'].points += [touch.x, touch.y]
        print(touch.spos,"Move")

    def on_touch_up(self, touch):
        print(touch.spos,"Up")
        ### 
        #while on_touch_up():
            #print(touch.spos,"Up")
        ###

class MyPaintApp(App):

    def build(self):
        return MyPaintWidget()


if __name__ == '__main__':
    MyPaintApp().run()

它打印:

((0.2175, 0.7716666666666667), 'Down')
((0.2175, 0.7716666666666667), 'Move')
((0.2175, 0.685), 'Move')
((0.2175, 0.5516666666666667), 'Move')
((0.2175, 0.4633333333333334), 'Move')
((0.2175, 0.44666666666666666), 'Move')
((0.2175, 0.44666666666666666), 'Up')
((0.2175, 0.43500000000000005), 'Down')
((0.23, 0.43500000000000005), 'Move')
((0.67, 0.5916666666666667), 'Up')

但是我想在输出中有更多的“ Up”(像每隔0.1s)。我用while尝试过time.sleep(),但是程序崩溃了。

1 个答案:

答案 0 :(得分:1)

我这样解决了。这不是最优雅的方法,但对我有用。

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Color, Ellipse, Line
from kivy.clock import Clock


class MyPaintWidget(Widget):

    def __init__(self,**kwargs):
        super(MyPaintWidget, self).__init__(**kwargs)
        Clock.schedule_interval(self.on_touch_up, 0.1)

    def on_touch_down(self, touch):
        with self.canvas:
            Color(1, 1, 0)
            touch.ud['line'] = Line(points=(touch.x, touch.y))
        print(touch.spos, "Down")

    a = []
    def on_touch_move(self, touch):
        touch.ud['line'].points += [touch.x, touch.y]
        print(touch.spos,"Move")
        self.a.append(touch.spos)

    def on_touch_up(self, dt):
        if not self.a:
            pass
        else:
            print(self.a[-1], "Up")
            if len(self.a) > 2:
                del self.a[0:-2]


class MyPaintApp(App):

    def build(self):
        return MyPaintWidget()


if __name__ == '__main__':
    MyPaintApp().run()