我们创建了一个名为ImageSelector
的QWidget子类,其中包含一个QPushButton和一个QLabel。当用户单击按钮时,我们使用QFileDialog让用户选择一个图像文件,并在QLabel中显示选择的图像。
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QFileDialog
from PyQt5.QtGui import QPixmap
class ImageSelector(QWidget):
def __init__(self):
super().__init__()
# 创建一个按钮,用于选择图像文件
self.select_btn = QPushButton('选择图片', self)
self.select_btn.clicked.connect(self.select_image)
# 创建一个标签,用于显示选择的图像
self.image_label = QLabel(self)
self.image_label.setGeometry(10, 60, 300, 300)
# 设置窗口的大小和标题
self.setGeometry(100, 100, 320, 380)
self.setWindowTitle('PyQt5 Image Selector')
def select_image(self):
# 弹出文件选择对话框,选择图像文件
filename, _ = QFileDialog.getOpenFileName(self, '选择图片', '.', 'Image files (*.jpg *.png *.gif)')
# 如果成功选择了文件,则在标签中显示该文件的图像
if filename:
pixmap = QPixmap(filename)
self.image_label.setPixmap(pixmap)
if __name__ == '__main__':
app = QApplication([])
selector = ImageSelector()
selector.show()
app.exec_()