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

Posted

技术标签:

【中文标题】Pyqt5 - 文件对话框GUI关闭后无法运行代码【英文标题】:Pyqt5 - can't run code after file dialog GUI has closed 【发布时间】:2018-02-08 20:58:47 【问题描述】:

我的代码旨在使用 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])

【问题讨论】:

那行代码永远不会被调用,当你拥有这两个文件时,你必须将该代码放在 GUI 中。 两个问题:(1)调用sys.exit会在脚本到达下面的代码之前终止脚本; (2) filepath 变量不是全局变量,因此不能在打开对话框方法之外访问。 【参考方案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])
# ...

【讨论】:

以上是关于Pyqt5 - 文件对话框GUI关闭后无法运行代码的主要内容,如果未能解决你的问题,请参考以下文章

单击文件名时 PyQt5 QFileDialog 关闭

PyQt5 (python) GUI 在运行 .exe 后崩溃,未解决的错误代码 0x80004005(未指定的错误)

PyQt5学习笔记2-GUI编程基础-2

PyQt5 GUI 无法正确加载

使用 PyQt5 制作应用程序后无法打开 .exe

无法使用pyqt5显示秒表