Screenshot of a window using python

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_()

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

Instead, you can use QWidget.grab()

p=widget.grab()

Tags:

Python

Pyqt