简体   繁体   English

有没有办法在 pyqt5 或 qt5 中截取窗口的屏幕截图?

[英]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..我需要一个跨平台方法..

Ref: http://doc.qt.io/qt-5/qscreen.html#grabWindow参考: 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.在这里不是合适的调用,因为它捕获了整个屏幕,根据最后的 4 个参数进行裁剪。 (the 100 parameters are width and height). (这 100 个参数是宽度和高度)。

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.我已经在 Windows 上测试过了。

If any one is coming here and having issues with the other answer, it might be a timing problem.如果有人来到这里并且对另一个答案有疑问,则可能是时间问题。

If you try to grab a screenshot directly during / after initializing the QWidget() instead of at the press of a button it might just make a screenshot of your desktop at the area of your window.如果您尝试在初始化QWidget()期间/之后直接截取屏幕截图,而不是在按下按钮时,它可能只会在窗口区域截取桌面的屏幕截图。

So if you want to grab a screenshot directly after calling __init__ , call it after waiting some time with a QTimer (do not use time.sleep() as this would block the GUI).因此,如果您想在调用__init__后直接截取屏幕截图,请在使用QTimer等待一段时间后调用它(不要使用time.sleep() ,因为这会阻塞 GUI)。

def initUI(self): 
    (...)       
    QTimer.singleShot(1000, self.saveScreenshot)

def saveScreenshot(self):
    screen = QApplication.primaryScreen()
    screenshot = screen.grabWindow(self.winId() )
    screenshot.save('screenshot.png', 'png')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM