Python 截图 2 个以上显示器(Windows)

9 投票
3 回答
10279 浏览
提问于 2025-04-16 22:52

如何用Python在连接多个显示器的情况下截屏?

我试过:

import sys
from PyQt4.QtGui import QPixmap, QApplication
app = QApplication(sys.argv)
QPixmap.grabWindow(QApplication.desktop().winId()).save('test.png', 'png')

import ImageGrab
im = ImageGrab.grab()
im.save('test.png', 'PNG')

这两种方法都只能截取主显示器的画面。

如果我使用winapi:

hWnd = win32gui.FindWindow(None, win_name)
dc = win32gui.GetWindowDC(hWnd)
i_colour = int(win32gui.GetPixel(dc,int(x),int(y)))
rgb = ((i_colour & 0xff), ((i_colour >> 8) & 0xff), ((i_colour >> 16) & 0xff))

我可以从第二个显示器的窗口获取图片,但速度会非常慢。

如果我按下'printscreen'键,剪贴板里会有一个正常的截图,包含所有显示器的内容。有没有办法在Python中获取完整的截图呢?

3 个回答

1
  • 安装 desktopmagic:
pip install Desktopmagic)
from __future__ import print_function
import desktopmagic
from desktopmagic.screengrab_win32 \
import(getDisplayRects,saveScreenToBmp,getScreenAsImage,getRectAsImage,getDisplaysAsImages)

""" getDisplayRects functions returns a list with all displays, in display order, like  [(0, 0, 1280, 1024), (-1280, 0, 0, 1024), (1280, -176, 3200, 1024)]  : (left, top, right, bottom)"""

screens=(getDisplayRects())
  • 对第二个显示器截图
rect = getRectAsImage(screens[1]) 
  • 0 代表第一个显示器,1 代表第二个显示器,依此类推...
#saves screenshot
rect.save('leftscr.png',format='png')
9

我的Desktopmagic库可以在Python 2.6、2.7和3.3及以上版本中使用。它可以返回一个PIL/Pillow格式的图片,或者写入一个BMP格式的文件。

6

这里提到的是使用wxPython、win32api和ctypes这几种工具的组合。

import wx, win32api, win32gui, win32con, ctypes

class App(wx.App):
    def OnInit(self):
        dll = ctypes.WinDLL('gdi32.dll')
        for idx, (hMon, hDC, (left, top, right, bottom)) in enumerate(win32api.EnumDisplayMonitors(None, None)):
            hDeskDC = win32gui.CreateDC(win32api.GetMonitorInfo(hMon)['Device'], None, None)
            bitmap = wx.EmptyBitmap(right - left, bottom - top)
            hMemDC = wx.MemoryDC()
            hMemDC.SelectObject(bitmap)
            try:
                dll.BitBlt(hMemDC.GetHDC(), 0, 0, right - left, bottom - top, int(hDeskDC), 0, 0, win32con.SRCCOPY)
            finally:
                hMemDC.SelectObject(wx.NullBitmap)
            bitmap.SaveFile('screenshot_%02d.bmp' % idx, wx.BITMAP_TYPE_BMP)
            win32gui.ReleaseDC(win32gui.GetDesktopWindow(), hDeskDC)
        return False

App(0)

撰写回答