Take screenshot in Python — Cross Platform

2019-01-23 18:06发布

问题:

I need to take a screenshot and send it via post to a web service. I think for the post part i will use liburl.

Can this be accomplished completely cross platform and without having the need for the final user to install additional libraries/software?

回答1:

There is not anything in the standard library that can do this for you. Theoretically, you might do it yourself by making os-dependent system calls with ctypes but that seems like a lot of unnecessary work to me. Here is a working script to make a screenshot using wxPython:

import wx

app = wx.App(False)

s = wx.ScreenDC()
w, h = s.Size.Get()
b = wx.EmptyBitmap(w, h)
m = wx.MemoryDCFromDC(s)
m.SelectObject(b)
m.Blit(0, 0, w, h, s, 0, 0)
m.SelectObject(wx.NullBitmap)
b.SaveFile("screenshot.png", wx.BITMAP_TYPE_PNG)


回答2:

You could also use PyQt5 for this:

import sys
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtWidgets import QApplication

app = QApplication(sys.argv)
screen = QGuiApplication.primaryScreen()
desktopPixmap = screen.grabWindow(0)
desktopPixmap.save('screendump.png')