有没有办法让 QPixmap 函数获取元组或使用 QFileDialog.getOpenFileName 函数?

Is there a way for the QPixmap function to take a tuple or work with the QFileDialog.getOpenFileName function?

我希望能够使用 QFileDialog 打开文件选择 window,以便选择图像并使用 PyQt5 在我的 window 中显示它。但是,我的错误总是说 "TypeError: QPixmap(): argument 1 has unexpected type 'tuple'"

这是代码行:

fname = QFileDialog.getOpenFileName(self, 'Open File', '/home', "Image Files (*.jpg *.png)")
self.labels.setPixmap(QPixmap(fname))

我尝试去掉 getOpenFileName 函数中的其他参数,只保留 self 关键字。除此之外,我还没有找到解决办法。

import sys
from PyQt5 import *
from PyQt5.QtCore import QObject, pyqtSlot
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QFileDialog, QVBoxLayout, QPushButton
from PyQt5.QtGui import QPixmap

class filePicker(QWidget):
    def __init__(self):
        super().__init__()
        vbox = QVBoxLayout()
        self.button = QPushButton("Upload Image", self)
        self.labels = QLabel(self)
        self.button.clicked.connect(self.on_click)
        vbox.addWidget(self.button)
        vbox.addWidget(self.labels)

        self.setLayout(vbox)
    @pyqtSlot()
    def on_click(self):
        fname = QFileDialog.getOpenFileName(self, 'Open File', '/home', "Image Files (*.jpg *.png)")
        self.labels.setPixmap(QPixmap(fname))


myApp = QApplication(sys.argv)
myWindow = filePicker()
myWindow.setGeometry(100, 100, 1200, 800)
myWindow.setWindowTitle("Hello")
myWindow.show()

sys.exit(myApp.exec_())

if __name__ == '__main__':
   main()

我希望显示我选择的图像,但我只收到错误消息:

TypeError: QPixmap(): argument 1 has unexpected type 'tuple'

在PyQt5中,QFileDialog.getOpenFileNamereturns两个参数作为一个元组。您可以解压第一个参数以接收图像文件的路径作为 str。更改

def on_click(self):
    fname = QFileDialog.getOpenFileName(self, 'Open File', '/home', "Image Files (*.jpg *.png)")
    self.labels.setPixmap(QPixmap(fname))

def on_click(self):
    fname, _ = QFileDialog.getOpenFileName(self, 'Open File', '/home', "Image Files (*.jpg *.png)")
    self.labels.setPixmap(QPixmap(fname))

嵌入图片