Search code examples
pythondirectorypyqt5jupyter

Python Jupyter - PyQt5 Selected File Paths Not Saved As Variables


I'm trying to create a dynamic files selector using PyQt5 in Jupyter Notebook, allowing users to select Microsoft Excel files to be read and loaded.

However, the Microsoft Excel file paths are not saved as variables after exiting the PyQt5 application by clicking the button or closing the window manually and moving to the next code block.

How do I save the file paths as variables after exiting the PyQt5 application?

Here is the code I've used so far:

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

def open_dialog_box():
    filenames, _ = QFileDialog.getOpenFileNames(
    None,
    "QFileDialog.getOpenFileNames()",
    "",
    "All Files (*);;Microsoft Excel Files (*.xls)",
)
    if filenames:
        for filename in filenames:
            print(str(filename))

def close_dialog_box():
    QtWidgets.QWidget().close()
        
app = QApplication(sys.argv)
win = QMainWindow()
win.setGeometry(300, 300, 600, 600)
win.setWindowTitle("WINDOW TITLE - SELECT THE FILES")
win.move(150, 150)
  
button1 = QPushButton(win)
button1.setGeometry(600, 600, 200, 200)
button1.setText("CLICK TO SELECT THE FILES")
button1.move(10, 10)
button1.clicked.connect(open_dialog_box)

button2 = QPushButton(win)
button2.setGeometry(600, 600, 200, 200)
button2.setText("CLICK TO EXIT")
button2.move(390, 10)
button2.clicked.connect(close_dialog_box)

win.show()
app.exec_()

Solution

  • Create a global variable, get the filepaths list once clicked

    FILE_PATHS = []
    def open_dialog_box():
        global FILE_PATHS
        filenames, _ = QFileDialog.getOpenFileNames(
            None,
            "QFileDialog.getOpenFileNames()",
            "",
            "All Files (*);;Microsoft Excel Files (*.xls)",
        )
        if filenames:
            FILE_PATHS = filenames
            for filename in filenames:
                print(str(filename))