如下图,这种矩形选择框在图形软件里是必备操作,用python怎么实现?我用wxpython 做了一个例子。
代码如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Project: test
# File : SelectRectang.py
# Author : Long.Xu <fangkailove@yeah.net>
# http://gnolux.blog.csdn.net
# QQ:26564303 weixin:wxgnolux
# Time : 2023/6/20 21:39
# Copyright 2023 Long.Xu All rights Reserved.
import wx
class MyFrame(wx.Frame):
def __init__(self, parent, id, title, pos=wx.DefaultPosition,
size=(1200, 800), style=wx.DEFAULT_FRAME_STYLE):
wx.Frame.__init__(self, parent, id, title, pos, size, style)
self._dragstartpos = None
self._dragendpos = None
self.Bind(wx.EVT_PAINT,self.OnPaint)
self.Bind(wx.EVT_MOUSE_EVENTS,self.OnMouseEvent)
def OnPaint(self,evt):
dc = wx.PaintDC(self)
#self.PrepareDC(dc)
dc.Clear()
if self._dragstartpos and self._dragendpos:
font: wx.Font = dc.GetFont()
x = min(self._dragendpos[0],self._dragstartpos[0])
y = min(self._dragendpos[1],self._dragstartpos[1])
w = abs(self._dragendpos[0]-self._dragstartpos[0])
h = abs(self._dragendpos[1]-self._dragstartpos[1])
pen = wx.Pen("red", 1, wx.PENSTYLE_USER_DASH)
pen.SetDashes([10,10])
dc.SetPen(pen)
dc.SetBrush(wx.Brush("white", wx.BRUSHSTYLE_TRANSPARENT))
# x,y=self.CalcUnscrolledPosition(x,y)
text = "x:%d,y:%d,w:%d,h:%d" % (x,y,w,h)
text_extent = self.GetFullTextExtent(text, font)
dc.DrawText(text, x+(w - text_extent[0]) // 2, y+(h - text_extent[1]) // 2)
dc.DrawRectangle(x,y,w,h)
dc.EndDoc()
def OnMouseEvent(self,event):
if event.ButtonDown():
if not self.HasCapture():
self.CaptureMouse()
self._dragstartpos = event.GetPosition()
# print(self._dragstartpos)
# self.FocusedMask.SetFocus()
elif event.Dragging() and self.HasCapture():
pt = event.GetPosition()
dx = pt[0] - self._dragstartpos[0]
dy = pt[1] - self._dragstartpos[1]
if event.LeftIsDown() and self._dragstartpos:
self._dragendpos = event.GetPosition()
self.Refresh()
elif event.ButtonUp():
if self.HasCapture():
self.ReleaseMouse()
if event.LeftUp() and self._dragendpos and self._dragstartpos:
w = abs(self._dragstartpos[0]-self._dragendpos[0])
h = abs(self._dragstartpos[1]-self._dragendpos[1])
x = min(self._dragstartpos[0],self._dragendpos[0])
y = min(self._dragstartpos[1],self._dragendpos[1])
if w>8 and h>8:
print("selection:",x,y,w,h)
self._dragstartpos = None
self._dragendpos = None
self.Refresh()
event.Skip()
if __name__ == '__main__':
app = wx.App()
frm = MyFrame(None, -1, "wxPython 矩形选择框 测试")
frm.Show()
app.MainLoop()