首页 > 解决方案 > 更好的 Kivy 点击拖拽画线

问题描述

这是一个更大的应用程序的一个小组件,当单击、拖动和释放时会画一条线:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.core.window import Window
from kivy.graphics import Color, Line, Rectangle

Window.set_system_cursor('crosshair')

DRAG_START = ()
DRAG_END = ()
DRAGGING = False


class Widget(BoxLayout):
    def __init__(self, **kwargs):
        super(Widget, self).__init__(**kwargs)
        Window.bind(mouse_pos=self.mouse_pos)
        self.bind(pos=self.draw)
        self.bind(size=self.draw)
        self.layout1 = BoxLayout(opacity=1)
        self.add_widget(self.layout1)

    def draw(self, *args):
        self.layout1.canvas.clear()
        with self.canvas.before:
            Color(0.6, 0.6, 0.6, 1)
            self.bg = Rectangle(pos=self.pos, size=self.size)

    def drawLine(self, mPos):
        self.canvas.clear()
        with self.canvas:
            Color(0, 0, 0, 1)
            Line(
                points=[DRAG_START[0], DRAG_START[1], mPos[0], mPos[1]],
                width=1.4)

    def mouse_pos(self, window, pos):
        if DRAGGING == True:
            self.drawLine(pos)

    def on_touch_down(self, event):
        global DRAGGING, DRAG_START
        DRAGGING = True
        DRAG_START = event.pos

    def on_touch_up(self, event):
        global DRAGGING, DRAG_END
        DRAGGING = False
        DRAG_END = event.pos


class App(App):
    title = "Kivy Click Drag Line"

    def build(self):
        return Widget()


if __name__ == "__main__":
    App().run()

结果是 :

在此处输入图像描述

虽然这可行,但我的问题是是否有更好的方法在 python 中执行此操作(对使用 kivy 语言不感兴趣)我有点怀疑我正在使用的全局变量以及在小部件中观察到的事件。

谢谢 !

标签: pythonuser-interfacekivymouseevent

解决方案


不能声称这是我自己的代码,但我已经使用了这个:

class Draw(Widget):
    def on_touch_down(self,touch):
        with self.canvas:
            touch.ud["line"]=Line(points=(touch.x,touch.y))
    def on_touch_move(self,touch):
        with self.canvas:
            touch.ud["line"].points +=(touch.x,touch.y)
    def on_touch_up(self,touch):
        print("released mouse",touch)

推荐阅读