Python window screenshot

I am trying to take a screenshot in the current window using python script in linux.

Now I have a script that takes a screenshot of the entire screen:

import sys from PyQt4.QtGui import QPixmap, QApplication from datetime import datetime date = datetime.now() filename = date.strftime('%Y-%m-%d_%H-%M-%S.jpg') app = QApplication(sys.argv) QPixmap.grabWindow(QApplication.desktop().winId()).save(filename, 'jpg') 

But I would like to have only the selected window. I know the problem comes from grabWindow. But I do not know how to solve it.

+6
source share
3 answers

just replace

 QApplication.desktop() 

with widgets you want to take off the screen.

 import sys from PyQt4.QtGui import * from datetime import datetime date = datetime.now() filename = date.strftime('%Y-%m-%d_%H-%M-%S.jpg') app = QApplication(sys.argv) widget = QWidget() # set up the QWidget... widget.setLayout(QVBoxLayout()) label = QLabel() widget.layout().addWidget(label) def shoot(): p = QPixmap.grabWindow(widget.winId()) p.save(filename, 'jpg') label.setPixmap(p) # just for fun :) print "shot taken" widget.layout().addWidget(QPushButton('take screenshot', clicked=shoot)) widget.show() app.exec_() 
+6
source

Since Qt5, grabWindow and grabWidget are deprecated (see Deprecated Members for QPixmap )

You can use QWidget.grab()

 p=widget.grab() 
+3
source

Alternatively instead

 p = QPixmap.grabWindow(widget.winId()) 

you can also use

 p = QPixmap.grabWidget(widget) 
0
source

Source: https://habr.com/ru/post/916369/


All Articles