本文介绍了使用 PyQt5 QLabel.setPixmap 后出现分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 QPixmap 和 QLabel 显示 PIL 图像.但是当我运行代码时,我得到了 SIGSEGV.代码:
I'm trying to show a PIL image using QPixmap and QLabel. But when I run the code, I get SIGSEGV.Code:
import sys
from PIL import Image
from PIL.ImageQt import ImageQt
from PyQt5 import QtWidgets
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication, QMainWindow
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
# im = Image.new('RGB', (200, 200), (255, 255, 255))
im = Image.new('RGB', (500, 500), (255, 255, 255))
self.label.setPixmap(QPixmap.fromImage(ImageQt(im)))
def setupUi(self, MainWindow):
MainWindow.resize(767, 557)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.layout = QtWidgets.QGridLayout(self.centralwidget)
self.label = QtWidgets.QLabel(self.centralwidget)
self.layout.addWidget(self.label, 0, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MainWindow()
ex.show()
sys.exit(app.exec_())
当我将图像大小更改为 200x200 时,它不会引发分割错误,而是随机着色像素.
When I change image size to 200x200, it doesn't throw segmentation fault but has randomly colorized pixels.
如何将我的 PIL 图像正确放入窗口?
How do I put my PIL image into a window correctly?
推荐答案
试试RGBA
格式:
import sys
from PIL import Image
from PIL.ImageQt import ImageQt
from PyQt5 import QtWidgets
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication, QMainWindow
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
# im = Image.new('RGB', (200, 200), (255, 255, 155))
# im = Image.new('RGB', (500, 500), (255, 255, 255))
im = Image.new("RGBA", (500, 500), (255, 155, 155, 255)) # <---
self.label.setPixmap(QPixmap.fromImage(ImageQt(im)))
def setupUi(self, MainWindow):
MainWindow.resize(767, 557)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.layout = QtWidgets.QGridLayout(self.centralwidget)
self.label = QtWidgets.QLabel(self.centralwidget)
self.layout.addWidget(self.label, 0, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MainWindow()
ex.show()
sys.exit(app.exec_())
这篇关于使用 PyQt5 QLabel.setPixmap 后出现分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!