windowspython-2.7pyqt4qfiledialoggetopenfilename

PyQt QFileDialog getOpenFileName not working from command line (windows)


I'm trying to make a gui (Qt Designer) to import an excel file and display the data in the gui.

The script works fine when I run it from within my IDE (Spyder), but if I run it from the command window or by opening the python file from windows explorer, the import function does not work. (The gui starts up fine but when the import button is pressed and the file is selected, nothing happens and no error is produced. When running from Spyder, the data is imported and displayed in the gui as expected).

If I pre-select the file location (commented out in the code below), then the script works fine from the command line or by clicking from explorer.

Thanks for any help!

Python 2.7 (Anaconda), Windows 10, PyQt4

import sys
from PyQt4 import QtGui
from excel_import_gui import Ui_MainWindow
import xlrd


class Main(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.setupSignals()      


    def set_import_data(self,data_to_import,table_to_change):
        for row in range(len(data_to_import)):
            for col in range(len(data_to_import[0])):
                table_to_change.setRowCount(len(data_to_import))
                table_to_change.setColumnCount(len(data_to_import[0]))
                item = data_to_import[row][col]      
                table_to_change.setItem(row,col,QtGui.QTableWidgetItem(str(item)))


    def setupSignals(self):
        self.ui.importData_btn.clicked.connect(self.select_file)


    def select_file(self):
        excel_file = QtGui.QFileDialog.getOpenFileName(self,
        "Select Excel file to import","","Excel (*.xls *.xlsx)")

#        excel_file = "C:/Users/Ben/Work/Python tests/Qt GUIs/Excel_import_GUI/fish_test.xlsx"


        if excel_file:
            open_excel_file = xlrd.open_workbook(excel_file)
            self.start_import_data(open_excel_file)


    def start_import_data(self, workbook):
        #import data from excel file 
        workbook_data = []
        for sheetNum in range (workbook.nsheets):
            worksheet = workbook.sheet_by_index(sheetNum)
            workbook_data.append([[worksheet.cell_value(row,col) for col in range (worksheet.ncols)] for row in range(worksheet.nrows)])

        # Set each worksheet of workbook_data to each tab in GUI widget
        self.set_import_data(workbook_data[0],self.ui.fish_table)
        self.set_import_data(workbook_data[1],self.ui.boats_table)


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = Main()
    window.show()
    sys.exit(app.exec_())

Solution

  • Well I found a solution myself by converting the excel_file variable to a string.

    excel_file = str(QtGui.QFileDialog.getOpenFileName(self, "Select Excel file to import","","Excel (*.xls *.xlsx)"))