8

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.

Alexis Bernard
  • 95
  • 1
  • 1
  • 5

4 Answers4

9

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_()
mata
  • 67,110
  • 10
  • 163
  • 162
7

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

Instead, you can use QWidget.grab()

p=widget.grab()
Mel
  • 5,837
  • 10
  • 37
  • 42
  • That's don't work in case you have a scroll area inside the MainWindow. It only prints the top part of window. – Chris P Sep 12 '20 at 03:17
0

Alternatively, instead of

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

you can also use

p = QPixmap.grabWidget(widget)
Ben
  • 1,638
  • 2
  • 14
  • 21
0

PyQt5 update

import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import 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')
Most Wanted
  • 6,254
  • 5
  • 53
  • 70