Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
978 views
in Technique[技术] by (71.8m points)

python - Is there a way to take screenshot of a window in pyqt5 or qt5?

#!/usr/bin/env python3
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QApplication, QWidget
import sys

app = QApplication(sys.argv)
screen = QApplication.primaryScreen()
widget = QWidget()

screenshot = screen.grabWindow(0, 0, 0, 100, 100)
screenshot.save('shot', 'jpg')

How can i use this to get a window? it only get a part of screen:

screenshot = screen.grabWindow( widget.winId() )

I need a crossplataform method..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ref: http://doc.qt.io/qt-5/qscreen.html#grabWindow

You say you require a screenshot of a window, therefore

screenshot = screen.grabWindow(0, 0, 0, 100, 100)

is not the appropriate call here, since it captures the entire screen, cropped according to the final 4 parameters. (the 100 parameters are width and height).

screenshot = screen.grabWindow( widget.winId() )

captures the widget window. However, the reason you don't perhaps get what you expected on this call is that you don't create a solid widget and/or the widget hasn't been shown. Try the following example, making sure the app is on your primary display before clicking the button.

from PyQt5 import QtWidgets
import sys

app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QWidget()

grab_btn=QtWidgets.QPushButton('Grab Screen')
def click_handler():
    screen = QtWidgets.QApplication.primaryScreen()
    screenshot = screen.grabWindow( w.winId() )
    screenshot.save('shot.jpg', 'jpg')
    w.close()

grab_btn.clicked.connect(click_handler)

layout = QtWidgets.QVBoxLayout()
layout.addWidget(grab_btn)
w.setLayout(layout)
w.show()

sys.exit(app.exec_())

I've tested this on Windows.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...