PyQt5实现本地图片查看器功能

在本教程中,我们将介绍如何基于PyQt5实现一个简单的本地图片查看功能。首先,使用QFileDialog选择本地图片文件,接着用QLabel来显示图片内容。代码示例如下:

import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout, QFileDialog

class ImageViewer(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('本地图片查看器')
        self.setGeometry(100, 100, 800, 600)

        self.layout = QVBoxLayout()
        self.label = QLabel(self)
        self.layout.addWidget(self.label)
        self.setLayout(self.layout)

        self.open_image()

    def open_image(self):
        file, _ = QFileDialog.getOpenFileName(self, '选择图片文件', '', 'Images (*.png *.xpm *.jpg)')
        if file:
            pixmap = QPixmap(file)
            self.label.setPixmap(pixmap.scaled(800, 600, Qt.KeepAspectRatio))

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = ImageViewer()
    window.show()
    sys.exit(app.exec_())
rar 文件大小:930.34KB