File Picker in PyQt: A Comprehensive Python GUI Tutorial (Lesson 14)

Posted by


In this tutorial, we will learn how to open files using a file picker dialog in a PyQt-based Python GUI application. This functionality can be useful when you want to allow users to select and open files from their computer.

To get started, make sure you have PyQt installed. You can install PyQt using pip:

pip install PyQt5

Next, create a new Python script and import the necessary modules:

import sys
from PyQt5.QtWidgets import QApplication, QFileDialog, QMainWindow, QPushButton

Now, create a main window class that will contain a button to open the file picker dialog:

class FilePickerWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.init_ui()

    def init_ui(self):
        self.setWindowTitle('File Picker Example')
        self.setGeometry(100, 100, 400, 200)

        self.btn = QPushButton('Open File', self)
        self.btn.setGeometry(150, 80, 100, 30)
        self.btn.clicked.connect(self.open_file)

    def open_file(self):
        file_dialog = QFileDialog()
        file_dialog.setFileMode(QFileDialog.ExistingFile)
        file_dialog.setNameFilter('All Files (*.*)')

        if file_dialog.exec_():
            file_path = file_dialog.selectedFiles()[0]
            print(f'Selected file: {file_path}')

In the open_file method, we create a QFileDialog instance and set the file mode to QFileDialog.ExistingFile, which allows the user to select an existing file. We then set the name filter to show all files (All Files (*.*)).

When the user selects a file and clicks the "Open" button in the file picker dialog, the selectedFiles() method returns a list of selected file paths. We extract the first file path from the list and print it to the console.

Finally, create an application instance and show the main window:

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = FilePickerWindow()
    window.show()
    sys.exit(app.exec_())

Now, when you run the script, a window will appear with a button labeled "Open File". Clicking this button will open a file picker dialog, allowing you to select a file. The selected file path will be printed to the console.

That’s it! You have successfully implemented file opening functionality using a file picker in a PyQt-based Python GUI application. I hope you found this tutorial helpful. Thank you for reading!

0 0 votes
Article Rating
21 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@keukenrol
3 months ago

Is it possible to use the file picker just to have it function as an include / import? I would like to use the file picker to add a python file which should be executed as soon as i press a button.

@lakshyarana67
3 months ago

bro how to have a recent file option, i mean i have tried something but, how to save the path of the recent file which was open, after the window is closed

@NikkieBiteMe
3 months ago

this was super useful! thanks a lot!!! ^^

@jon-gavinharris6711
3 months ago

I know this is a bit old, but I was wondering how to exit the editor once you're done editing? I would like to be able to view a data set, and then close the editor and return to the app, Thank you

@aashimagupta9207
3 months ago

Hi buddy,
I really want to go with a simple approach and i am finding it tricky.
So, i have a set of python files in a folder and now i want a presentable GUi to run them. Also,
i want that on a click of button a particular python file should start running automatically Accepting the data from text field, without having to run them from command prompt.
How should i go for it??
I have Python 2.7 so which PyQt should i choose??
Please Help

@imgestudyo4399
3 months ago

can you make python pyqt5 image thumbnails viewer tutorials

@f.j.bradman1761
3 months ago

thanks for your lecture

@exosoul
3 months ago

I get an error when opening the file.  Can someone please help?  Error below:

Traceback (most recent call last):
    File "file location here.py", line 101, in file_open
        file = open(name, 'r')
TypeError: coercing to Unicode: need string or buffer, tuple found

@AbdoRoshdy95
3 months ago

hi can i get this code !

@carlfranz6805
3 months ago

Still. We have a font selector which does not do anything to the text in the editor. So, we have a bunch of really cool stuff which does not integrate.

@techminded5778
3 months ago

When I go to open the file, it returns an error saying my file is an invalid file type. Does anyone know how to fix this? Thanks.

@finalfantasy7820
3 months ago

In order to handle the error of 'Cancel' option or selecting a non-txt file: if (name != '') and (name.find('.txt') != -1):

@Pooja_Pandita
3 months ago

how to use a file chooser in qt designer…plzz help

@dpoca
3 months ago

Best videos ever

@powersang6114
3 months ago

In case some of you cannot read the text file by your editor, it may due to the
QtGui.QFileDialog.getOpenFileName(self, 'Open File')
returns a tuple of 2 elements:
name = QtGui.QFileDialog.getOpenFileName(self, 'Open File')
return
(u'C:/Users/username/filename.sth', u'All Files (.)')
so you may change the line

file = open(name, 'r')

to

file = open(name[0], 'r')

This should work. I am using python 2.7

@Kenwaldek
3 months ago

I have ported the lesson1 to lesson15 to PyQt5 you can find it https://github.com/kenwaldek/pythonprogramming

@nplus29
3 months ago

in Qt5, you have to do it this way:
「name, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Open File")」

@anaamorim2417
3 months ago

Hi! Cool channel very useful! I am having a lot of trouble with the module wishbone for python, have you ever come across it? There is a python GUI now available for Wishbone but I cannot open it and I dont know even how, the code is $> wishbone_gui.py . Thanks Best Ana

@gluedtogames
3 months ago

I'm trying to build a twitter application where you can either choose to update your status with text or with a picture file. I have the command version of this working perfectly, I just want to turn it into a gui. Is this tutorial in the right direction? I want to be able to browse to an image only and then tweet it.

@user-sw9bk5sk4j
3 months ago

should we close() the file after open it?