本文介绍了有没有办法在 pyqt5 或 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

你说你需要一个窗口的屏幕截图,因此

You say you require a screenshot of a window, therefore

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

在这里不是合适的调用,因为它捕获了整个屏幕,根据最后的 4 个参数进行裁剪.(这 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_())

我已经在 Windows 上测试过了.

I've tested this on Windows.

这篇关于有没有办法在 pyqt5 或 qt5 中截取窗口的屏幕截图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 20:59