Screenshot of a window using python

后端 未结 4 2158
清酒与你
清酒与你 2020-12-03 08:47

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:

相关标签:
4条回答
  • 2020-12-03 09:16

    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')
    
    0 讨论(0)
  • 2020-12-03 09:30

    Alternatively, instead of

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

    you can also use

    p = QPixmap.grabWidget(widget)
    
    0 讨论(0)
  • 2020-12-03 09:39

    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_()
    
    0 讨论(0)
  • 2020-12-03 09:42

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

    Instead, you can use QWidget.grab()

    p=widget.grab()
    
    0 讨论(0)
提交回复
热议问题