Skip to content Skip to sidebar Skip to footer

Screenshot Of A Window Using Python

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.Q

Solution 1:

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 forfun :)
    print "shot taken"

widget.layout().addWidget(QPushButton('take screenshot', clicked=shoot))

widget.show()
app.exec_()

Solution 2:

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

Instead, you can use QWidget.grab()

p=widget.grab()

Solution 3:

Alternatively, instead of

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

you can also use

p = QPixmap.grabWidget(widget)

Solution 4:

PyQt5 update

import sys
fromPyQt5.QtWidgetsimport QApplication
fromPyQt5.QtGuiimport QPixmap, QScreen
from datetime import datetime

date = datetime.now()
filename = date.strftime('%Y-%m-%d_%H-%M-%S.jpg')
app = QApplication(sys.argv)
QScreen.grabWindow(app.primaryScreen(), 
QApplication.desktop().winId()).save(filename, 'png')

Post a Comment for "Screenshot Of A Window Using Python"