geekdoc-python-zh/docs/pythonbasics/096.md

1.6 KiB
Raw Permalink Blame History

PyQT QPixmap

原文: https://pythonbasics.org/PyQT-QPixmap/

QPixmap可用于在 PyQT 窗口中显示图像。QPixmap()可以加载图像,因为它具有文件名作为参数。 要显示图像,请将QPixmap添加到QLabel

QPixmap支持所有主要的图像格式BMPGIFJPGJPEGPNGPBMPGMPPMXBM 和 XPM。

PyQT 图片

QPixmap

首先创建一个QPixmap和一个QLabel。 然后,您可以像这样组合它们:

self.im = QPixmap("./image.jpg")
self.label = QLabel()
self.label.setPixmap(self.im)

然后将整个内容添加到布局中,例如QGridLayout

self.grid = QGridLayout()
self.grid.addWidget(self.label,1,1)
self.setLayout(self.grid)

image

示例

复制并粘贴下面的代码,以从本地计算机加载图像。 该图像将以网格布局显示。

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QGridLayout, QWidget
from PyQt5.QtGui import QPixmap

class Example(QWidget):

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

        self.im = QPixmap("./image.jpg")
        self.label = QLabel()
        self.label.setPixmap(self.im)

        self.grid = QGridLayout()
        self.grid.addWidget(self.label,1,1)
        self.setLayout(self.grid)

        self.setGeometry(50,50,320,200)
        self.setWindowTitle("PyQT show image")
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

下载示例