这是较大应用程序的一小部分,在单击,拖动和释放时会画一条线:
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语言不感兴趣),我有点怀疑正在使用的全局变量以及在小部件中观察到的事件。
谢谢!
答案 0 :(得分:1)
不能将其声明为我自己的代码,但是我已经使用了它:
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)