我目前有一个 PIL 图像,我想将其显示在 PyQt 窗口上。我知道这一定很容易,但我找不到任何地方可以做到这一点。有人可以帮我解决这个问题吗? 这是我当前拥有的窗口的代码:
import sys
from PyQt4 import QtGui
class Window(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Window')
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
编辑:根据使用 Qt 和 Python 进行快速 GUI 编程:
According to PyQt’s documentation, QPixmaps are optimized for on-screen display (so they are fast to draw), and QImages are optimized for editing (which is why we have used them to hold the image data).
我有一个复杂的算法,可以生成我想在窗口上显示的图片。它们的创建速度非常快,因此对于用户来说,它们看起来就像一个动画(每秒可能有 15 个以上、20 个以上)。我应该使用 QPixmaps 还是 QImages?
最佳答案
尝试这样的事情,你可以使用http://svn.effbot.org/public/stuff/sandbox/pil/ImageQt.py将任何 pil 图像转换为 qimage
import sys
from PyQt4 import QtGui
from PIL import Image
def get_pil_image(w, h):
clr = chr(0)+chr(255)+chr(0)
im = Image.fromstring("RGB", (w,h), clr*(w*h))
return im
def pil2qpixmap(pil_image):
w, h = pil_image.size
data = pil_image.tostring("raw", "BGRX")
qimage = QtGui.QImage(data, w, h, QtGui.QImage.Format_RGB32)
qpixmap = QtGui.QPixmap(w,h)
pix = QtGui.QPixmap.fromImage(qimage)
return pix
class ImageLabel(QtGui.QLabel):
def __init__(self, parent=None):
QtGui.QLabel.__init__(self, parent)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Window')
self.pix = pil2qpixmap(get_pil_image(50,50))
self.setPixmap(self.pix)
app = QtGui.QApplication(sys.argv)
imageLabel = ImageLabel()
imageLabel.show()
sys.exit(app.exec_())
关于python - 如何在 PyQt 上的窗口上加载位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1713306/