Pyqt5 - 文件对话框GUI关闭后无法运行代码

时间:2018-02-08 20:58:47

标签: python pyqt5

我的代码是用Pyqt的openFileNameDialog手动选择两个.csv文件(在不同的文件夹中),然后继续执行不涉及GUI的代码。我可以让文件选择窗口运行并选择文件名,但代码不再处理。我究竟做错了什么?感谢

import pandas as pd
import numpy as np
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QFileDialog

class App(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):        
        self.openFileNameDialog()
        self.openFileNameDialog2()

    def openFileNameDialog(self):
        print('Getting file 1 location')
        filepath, _ = QFileDialog.getOpenFileName(self, "Open report 1", "", "csv (*.csv)")
        print('File 1 location: ',filepath)

    def openFileNameDialog2(self):
        print('Getting file 2 location')
        filepath2, _ = QFileDialog.getOpenFileName(self, "Open report 2", "", "csv (*.csv)")
        print('File 2 location: ',filepath2)

    def closeEvent(self):
        super(QWidget,self).closeEvent()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())

### The code doesn't run past this point
file1 = pd.read_csv(filepath, encoding='utf-8')
print(file1[0])

file2 = pd.read_csv(filepath2, encoding='utf-8')
print(file2[0])

1 个答案:

答案 0 :(得分:-1)

例如:

# ...
def openFileNameDialog(self):
    print('Getting file 1 location')
    filepath, _ = QFileDialog.getOpenFileName(self, "Open report 1", "", "csv (*.csv)")
    print('File 1 location: ',filepath)

    # read file1
    file1 = pd.read_csv(filepath, encoding='utf-8')
    print(file1[0])

def openFileNameDialog2(self):
    print('Getting file 2 location')
    filepath2, _ = QFileDialog.getOpenFileName(self, "Open report 2", "", "csv (*.csv)")
    print('File 2 location: ',filepath2)

    # read file2
    file2 = pd.read_csv(filepath2, encoding='utf-8')
    print(file2[0])
# ...