Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Screenshot of a window using python

Tags:

python

pyqt

I'm trying to take a screenshot of the curent window using a python script on linux.

I curently have a script which 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 a would like to have only the selected window. I know that the problem comes from grabWindow. But I don't know how to resolve it.

like image 542
Alexis Bernard Avatar asked May 22 '12 16:05

Alexis Bernard


2 Answers

simply replace

QApplication.desktop()

with the widget you want to take the screenshot of.

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_()
like image 79
mata Avatar answered Sep 24 '22 02:09

mata


Since Qt5, grabWindow and grabWidget are obsolete (see Obsolete Members for QPixmap)

Instead, you can use QWidget.grab()

p=widget.grab()
like image 43
Mel Avatar answered Sep 26 '22 02:09

Mel