Python创建一个GUI(PyQt5)选择文件的界面获取文件路径

我们在利用Python进行创建文件时经常会用到一些文件路径,我们可以创建一个选择文件路径GUI(PyQt5)界面,然后我们就可以获取文件的路径,我们以后就可以直接拿来用!!

如下视频演示

请添加图片描述

程序逻辑

1、点击【选择路径可以选择文件】

2、【确定(开始执行)】这个按钮没有绑定函数,大家可以根据自己的需求绑定函数

这样一来我们就可以获取文件的路径,并且可以传递给其他的函数内,并对该文件进行处理

完整版代码:

from PyQt5.QtWidgets import QApplication, QLabel, QPushButton, QLineEdit, QMainWindow, QFileDialog
import sys


class PathSelector(QMainWindow):
    def __init__(self):
        super().__init__()
        self.title = "路径选择"
        self.width = 500
        self.height = 300
        self.initUI()
        self.filePaths = []


    def initUI(self):
        # 设置窗口属性
        self.setWindowTitle(self.title)
        self.setGeometry(100, 100, self.width, self.height)

        # 标签组件
        self.label = QLabel(self)
        self.label.setText("选择文件:")
        self.label.move(50, 80)

        # 输入框控件
        self.entry_text = QLineEdit(self)
        self.entry_text.setFixedSize(250, 30)
        self.entry_text.move(150, 80)

        self.entry_text.setReadOnly(True)

        # 选择路径按钮
        self.button = QPushButton(self)
        self.button.setText('选择路径')
        self.button.move(400, 80)

        self.button.clicked.connect(self.get_path)

        # 确定按钮
        self.submit_button = QPushButton(self)
        self.submit_button.setText('确定(开始执行)')
        self.submit_button.move(155, 150)
        self.submit_button.clicked.connect(self.processing_data)
        self.show()

    # 获取文件路径
    def get_path(self):
        path1, _ = QFileDialog.getOpenFileName(self, "请选择文件", "", "All Files (*);;Text Files (*.txt)")
        self.entry_text.setText(path1)
        self.filePaths.append(path1)
        # print(self.filePaths)

    def processing_data(self):
        file_name = self.filePaths[0]
        print(file_name)
        '''
        
        这里就是你刚刚获取的文件的处理函数,点击【确定】按钮就会开始执行
        
        '''
        pass


if __name__ == "__main__":
    app = QApplication(sys.argv)
    ex = PathSelector()

    sys.exit(app.exec_())

希望对大家有帮助

致力于办公自动化的小小程序员一枚#

都看到这了,关注+点赞+收藏=不迷路!!

如果你想知道更多关于Python办公自动化的知识各位大佬给个关注吧!

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

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

(0)
青葱年少的头像青葱年少普通用户
上一篇 2023年11月7日
下一篇 2023年11月7日

相关推荐