我试图使用Wx和PyAutoGui模块制作一个剪切工具,我遇到了一个问题:保存的图像文件在错误的位置(见下图)
图片链接
正如你所看到的,我试图抓取一个特定区域,即红色矩形,并将该区域中的像素保存到文件“my_screenshot.png”中。但是,位置/坐标似乎是关闭的(您可以看到矩形,它应该是屏幕截图的区域)
代码如下:
import wx
import pyautogui
class SelectableFrame(wx.Frame):
c1 = None
c2 = None
def __init__(self, parent=None, id=-1, title=""):
wx.Frame.__init__(self, parent, id, title, size=wx.DisplaySize())
self.panel = wx.Panel(self, size=self.GetSize())
self.panel.Bind(wx.EVT_MOTION, self.OnMouseMove)
self.panel.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown)
self.panel.Bind(wx.EVT_LEFT_UP, self.OnMouseUp)
self.panel.Bind(wx.EVT_PAINT, self.OnPaint)
self.SetCursor(wx.Cursor(wx.CURSOR_CROSS))
self.SetTransparent(50)
def OnMouseMove(self, event):
if event.Dragging() and event.LeftIsDown():
self.c2 = event.GetPosition()
self.Refresh()
def OnMouseDown(self, event):
self.c1 = event.GetPosition()
def OnMouseUp(self, event):
self.SetCursor(wx.Cursor(wx.CURSOR_ARROW))
region = (self.c1.x, self.c1.y, self.c2.x - self.c1.x, self.c2.y - self.c1.y)
pyautogui.screenshot('my_screenshot.png', region=region)
print("MouseUp: " + str(region))
self.Hide()
def OnPaint(self, event):
if self.c1 is None or self.c2 is None: return
dc = wx.PaintDC(self.panel)
dc.SetPen(wx.Pen('red', 1))
dc.SetBrush(wx.Brush(wx.Colour(0, 0, 0), wx.TRANSPARENT))
region = (self.c1.x, self.c1.y, self.c2.x - self.c1.x, self.c2.y - self.c1.y)
dc.DrawRectangle(self.c1.x, self.c1.y, self.c2.x - self.c1.x, self.c2.y - self.c1.y)
print("Draw: " + str(region))
def PrintPosition(self, pos):
return str(pos.x) + " " + str(pos.y)
class MyApp(wx.App):
def OnInit(self):
frame = SelectableFrame()
frame.Show(True)
self.SetTopWindow(frame)
return True
app = MyApp(0)
app.MainLoop()
从我收集的数据来看,它需要宽度和高度,但是x和y的位置不对,我怎么能修正呢?非常感谢。
编辑:这些函数之间似乎存在值差异
def OnMouseDown(self, event):
self.c1 = event.GetPosition()
print("MouseDown[event]: " + str(self.c1))
print("MouseDown[gui]: "+ str(pyautogui.position()))
输出:
MouseDown[event]: (729, 484)
MouseDown[gui]: Point(x=737, y=515)
x的偏移量为8,y的偏移量为31。这种尿失禁是怎么发生的?我的修补程序是将这些偏移量添加到pyautogui中。屏幕截图命令,但我不认为这是正确的修复,也不能保证其他屏幕大小的偏移值相同。。
wxpython MouseEvent文档告诉我们
与鼠标事件关联的位置以生成事件的窗口的窗口坐标表示,您可以使用wx。窗ClientToScreen
将其转换为屏幕坐标,并可能调用wx。窗ScreenToClient
下一步,将其转换为另一个窗口的窗口坐标。
pyautogui“screenshot()
可用于屏幕坐标。
因此,使用wx。窗客户端使用
c1
和c2
进行屏幕显示。
顺便说一句,您也应该在mouseup上更新c2
,并检查它是否为“无”或等于c1
。