Search code examples
python-3.xpyqt5qpixmapqfiledialog

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


I want to be able to open up the file-picking window using QFileDialog in order to choose an image and display it in my window using PyQt5. However, my error is always saying "TypeError: QPixmap(): argument 1 has unexpected type 'tuple'"

Here is the line of code:

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

I've tried getting rid of the other parameters in the getOpenFileName function and leaving just the self keyword. Other than that, I haven't found a solution.

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()

I expect to display an image of my choosing but I only get the error:

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

Solution

  • In PyQt5, QFileDialog.getOpenFileName returns two parameters as a tuple. You can unpack the first parameter to receive the path of the image file as a str. Change

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

    to

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

    Embedded image