213.md 1.7 KB
Newer Older
W
wizardforcel 已提交
1
# PyQt5 图像
W
wizardforcel 已提交
2 3 4 5 6

> 原文: [https://pythonspot.com/pyqt5-image/](https://pythonspot.com/pyqt5-image/)

PyQt5(和 Qt)默认情况下支持图像。 在本文中,我们将向您展示如何向窗口添加图像。 可以使用 QPixmap 类加载图像。

W
wizardforcel 已提交
7 8 9
## PyQt5 图像简介

将图像添加到 [PyQt5](https://pythonspot.com/pyqt5/) 窗口就像创建标签并将图像添加到该标签一样简单。
W
wizardforcel 已提交
10

W
wizardforcel 已提交
11
```py
W
wizardforcel 已提交
12 13 14 15 16 17 18 19 20 21 22
label = QLabel(self)
pixmap = QPixmap('image.jpeg')
label.setPixmap(pixmap)

# Optional, resize window to image size
self.resize(pixmap.width(),pixmap.height())

```

这些是必需的导入:

W
wizardforcel 已提交
23
```py
W
wizardforcel 已提交
24 25 26 27 28 29 30
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QIcon, QPixmap

```

![pyqt5 qpixmap](img/7c8aa302666166e4fa6969572c501f04.jpg)

W
wizardforcel 已提交
31
## PyQt5 加载图像(`QPixmap`)
W
wizardforcel 已提交
32 33 34

复制下面的代码并运行。 该映像应与程序位于同一目录中。

W
wizardforcel 已提交
35
```py
W
wizardforcel 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QIcon, QPixmap

class App(QWidget):

    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 image - pythonspot.com'
        self.left = 10
        self.top = 10
        self.width = 640
        self.height = 480
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        # Create widget
        label = QLabel(self)
        pixmap = QPixmap('image.jpeg')
        label.setPixmap(pixmap)
        self.resize(pixmap.width(),pixmap.height())

        self.show()

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

```

[下载 PyQT5 示例](https://pythonspot.com/download-pyqt5-examples/)