gpt4 book ai didi

python - 尝试在标签中显示图像时 setPixmap 崩溃

转载 作者:行者123 更新时间:2023-12-02 19:33:52 32 4
gpt4 key购买 nike

我使用 pyqt 设计器创建了一个最小的示例,该示例在按下按钮时更改标签的文本,并且应该通过标签在窗口中显示屏幕截图。

不幸的是,该示例在尝试在标签中显示屏幕截图时崩溃了。

from PIL.ImageQt import ImageQt
from PyQt5 import QtCore, QtGui, QtWidgets
from pyscreenshot import grab

class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(503, 382)
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(70, 30, 75, 23))
self.pushButton.setObjectName("pushButton")
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(80, 100, 47, 14))
self.label.setObjectName("label")

self.retranslateUi(Form)
self.pushButton.clicked.connect(lambda: self.take_screenshot())
QtCore.QMetaObject.connectSlotsByName(Form)

def take_screenshot(self):
self.label.setText("1?")
screenshot = grab()
self.label.setText("2")
qim = ImageQt(screenshot)
pix = QtGui.QPixmap.fromImage(qim)
self.label.setText("3")
self.label.setPixmap(pix)



def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.pushButton.setText(_translate("Form", "PushButton"))
self.label.setText(_translate("Form", "TextLabel"))


if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())

最佳答案

“screenshot”与“qimg”共享相同的内存,并且作为屏幕截图,它是一个局部变量,当消除时,关联的内存也会被消除,因此当尝试访问信息时,QLabel 的 QPbelmap 将生成一个段错误。。解决方案是制作一个副本,这样它们就不会共享相同的内存

def take_screenshot(self):
screenshot = grab()
qim = ImageQt(screenshot)<b>.copy()</b>
pix = QtGui.QPixmap.fromImage(qim)
self.label.setPixmap(pix)
self.label.adjustSize()

关于python - 尝试在标签中显示图像时 setPixmap 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61354609/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com