使用pyqt、setPixmap和QLab的Python崩溃

2024-05-19 13:08:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Windows7 64位机器上使用了这个python代码,它只显示随机生成的黑白图像。如果我使图像大于511x511像素,我的Python2.7控制台崩溃。不过,在我的Mac电脑上运行得很好。有什么想法吗?在

import sys
from PyQt4 import QtGui, QtCore
import numpy as np


class PixmapTest(QtGui.QWidget):

    def __init__(self):
        super(PixmapTest, self).__init__()

        imglayout = QtGui.QHBoxLayout(self)

        size = 512
        img_8bit = (256*np.random.random((size,size))).astype(np.uint8)     

        img = QtGui.QImage(img_8bit.repeat(4), size, size, QtGui.QImage.Format_RGB32)

        pixmap = QtGui.QPixmap(img)

        imglabel = QtGui.QLabel(self)
        imglabel.setPixmap(pixmap)

        imglayout.addWidget(imglabel)
        self.setLayout(imglayout)

        self.show()        

def main():

    app = QtGui.QApplication(sys.argv)
    form = PixmapTest()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

Tags: 图像importselfimgsizeinitmaindef
1条回答
网友
1楼 · 发布于 2024-05-19 13:08:41

奇怪的是,对我来说(Win7,64位)截止大小接近300。我不知道它为什么会这样,但在我的例子中,我可以通过在应用程序上调用processEvents来修复它,如下所示:

class PixmapTest(QtGui.QWidget):
    def __init__(self, app):
        super(PixmapTest, self).__init__()
        self.app = app
        imglayout = QtGui.QHBoxLayout(self)
        size = 333
        img_8bit = (256*np.random.random((size,size))).astype(np.uint8)     
        img = QtGui.QImage(img_8bit.repeat(4), size, size, QtGui.QImage.Format_RGB32)
        pixmap = QtGui.QPixmap(img)
        imglabel = QtGui.QLabel(self)
        imglabel.setPixmap(pixmap)
        imglayout.addWidget(imglabel)
        self.setLayout(imglayout)
        self.show()        
        self.app.processEvents()

def main():
    app = QtGui.QApplication(sys.argv)
    form = PixmapTest(app)
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

相关问题 更多 >