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)

  • 5
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值