python - 更好的 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 语言不感兴趣)我有点怀疑我正在使用的全局变量以及在小部件中观察到的事件。
谢谢 !
解决方案
不能声称这是我自己的代码,但我已经使用了这个:
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)
推荐阅读
- python - 调试嵌入式 Python
- python - Python 执行速度慢
- javascript - 如何使用不同的 jest.config.js 进行单元和组件测试?
- c++ - 如何在 QFileDialog 中过滤带有空格字符的文件名?
- android - Google Play 服务是否可针对任何智能手机独立更新?Covid-19 的暴露通知 API 错误
- java - ArrayList 递归不考虑重复元素
- mysql - 斯特拉皮。Mysql 批量更新
- mongodb - mongoose jest 和超级用户 5000 毫秒后错误超时
- vespa - 无法将 vespa 指标推送到 cloudwatch
- javascript - 如何将 socket.id 关联到数组项?