我正在尝试使用QPixmap和QLabel显示PIL图像。但是当我运行代码时,我得到了SIGSEGV。代码:
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时,它不会引发分割错误,但是具有随机着色的像素。
如何将我的PIL图像正确放置到窗口中?
尝试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_())