从excel文件读取PyQT中的数据时出错:GtkDialog映射时没有临时父级不鼓励

问题描述

我尝试从excel文件中读取数据框并在单击按钮后将其打印。

import sys
from PyQt5 import QtCore,QtGui,QtWidgets
from PyQt5.QtWidgets import QApplication,QWidget,QPushButton,QMessageBox
from PyQt5.QtGui import QIcon
from excel_reading import *


class MyWin(QtWidgets.QMainWindow,Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.pushButton.clicked.connect(self.hello)

    def hello(self):
        data_input_from_file = QtWidgets.QFileDialog.getopenFileName(self,'header','filename','Excel (*.xlsx *.xls)')
        print(data_input_from_file)



if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    myapp = MyWin()
    myapp.show()
    sys.exit(app.exec_())

当我单击按钮时,会显示以下消息:

Gtk-Message: 00:03:53.573: GtkDialog mapped without a transient parent. This is discouraged.
('','')

我应该如何解决这个问题?

I solved the problem: 
    def hello(self):
        data_input_from_file = QtWidgets.QFileDialog.getopenFileName(self,'Excel (*.xlsx *.xls)')
        print(type(data_input_from_file))
        print(data_input_from_file)
        print(pd.read_excel(data_input_from_file[0]))

解决方法

Gtk警告正好是:警告。您可以忽略它。 Qt尝试尽可能使用系统的 native 文件对话框,这可能会在consolle输出中导致一些警告。

您的问题与其他问题有关:在某些罕见案例中,PyQt函数未返回与官方Qt(C ++)文档中报告的签名相同的签名。

QFileDialog静态方法就是这种情况之一,因为QFileDialog.getOpenFileName()总是返回一个元组:选定的文件路径和选定的文件类型过滤器。从您的代码输出中也可以清楚地看到(我想这是由于取消对话框引起的):

('','')

第一个值是选定的文件(在这种情况下为无)和过滤器(再次为无,因为没有选定的文件)。

解决方案是为静态返回值分配两个值:

    filePath,filters = QtWidgets.QFileDialog.getOpenFileName(
        self,'header','filename','Excel (*.xlsx *.xls)')
    if filePath:
        # do something