PyQt5通过按钮获取文件的路径

1.需求

python读写文件需要文件的路径,现在想要通过一个按钮让用户选择需要用到的文件,以获取它的路径信息。类似于下图的界面:
效果图

2.PyQt5的代码和说明

2.1代码

以下的代码可直接复制使用

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QFormLayout, QRadioButton
from PyQt5.QtWidgets import QFileDialog


class MyWindow(QtWidgets.QWidget):
    def __init__(self):
        super(MyWindow, self).__init__()
        # 读取Excel文件路径按钮
        self.chose_excel_button = QtWidgets.QPushButton()
        self.chose_excel_button.setObjectName("GetExcelPathButton")
        self.chose_excel_button.setText("请选择读取的Excel文件")
        # 工具界面日志
        self.log_TextEdit = QtWidgets.QTextEdit()
        # 业务相关
        self.excel_path = None

    def main_window(self):
        self.setWindowTitle("选取文件")
        form_layout = QFormLayout()
        form_layout.addRow(self.chose_excel_button)
        self.chose_excel_button.setCheckable(True)
        self.chose_excel_button.clicked.connect(lambda: self.click_find_file_path(self.chose_excel_button))
        form_layout.addRow("日志信息:", self.log_TextEdit)
        self.setLayout(form_layout)

    def click_find_file_path(self, button):
        # 设置文件扩展名过滤,同一个类型的不同格式如xlsx和xls 用空格隔开
        filename, filetype = QFileDialog.getOpenFileName(self, "选取Excel文件", "./data",
                                                         "Excel Files (*.xls *.xlsx)")
        if button.text() == "请选择读取的Excel文件":
            if button.isChecked():
                self.excel_path = filename
                self.log_TextEdit.append("需要读取的Excel路径为:" + filename)
                self.log_TextEdit.append("文件格式为:" + filetype)
        button.toggle()


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    main = MyWindow()
    main.main_window()
    main.show()
    sys.exit(app.exec_())

2.2关键函数说明

filename, filetype = QFileDialog.getOpenFileName(self, "选取Excel文件", "./data",
                                                         "Excel Files (*.xls *.xlsx)")

QFileDialog.getOpenFileName返回的是一个元组,该元组存贮你选择的文件的绝对路径,和该文件的文件类型。
效果展示
第一个参数parent,用于指定父组件,一般是一个窗口,在这个窗口建立选择文件的对话框。这里是self。
第二个参数caption,定义这个选择文件的对话框的标题。这里是读取Excel文件。
第三个参数dir,是对话框显示时默认打开的目录。这里是当前文件夹下的data文件夹。
第四个参数filter,用于文件对话框中文件的选择类型范围。这里是只能选择 .xls .xlsx文件。
可以根据不同场景设计可选文件类型。
比如支持所有文件,本参数可以写

All Files (*)

比如想要将xls和xlsx区分开,本参数可以写,注意是使用两个“;”隔开的

XLS File(.xls);;XLSX File(.xlsx)

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
社会演员多的头像社会演员多普通用户
上一篇 2023年3月29日
下一篇 2023年3月29日

相关推荐