python pyqt5 打开文件夹 读取文件列表

在这里插入图片描述

成员变量初始化

    def __init__(self, parent=None):
        super().__init__(parent)

        self.file_paths = []  # 文件列表
        self.file_index = 0	  # 文件索引

导入文件夹

    # 导入文件夹
    @pyqtSlot()
    def on_btnImportFolder_clicked(self):

        cur_dir = QDir.currentPath()  # 获取当前文件夹路径
        # 选择文件夹
        dir_path = QFileDialog.getExistingDirectory(self, '打开文件夹', cur_dir)

        # 读取文件夹文件
        self.file_paths.clear()
        for root, dirs, files in os.walk(dir_path, topdown=False):
            for file in files:
                self.file_paths.append(os.path.join(root, file))

        print(self.file_paths)
        if len(self.file_paths) <= 0:
            return

        # 获取第一个文件
        self.file_index = 0
        cur_path = self.file_paths[self.file_index]
		
		# 处理文件
        self.process_image(cur_path)

下一个文件

    # 下一个文件
    @pyqtSlot()
    def on_btnFolderNext_clicked(self):
        # 文件索引累加 1
        self.file_index += 1
        if self.file_index >= len(self.file_paths):
            self.file_index = len(self.file_paths) - 1

        if len(self.file_paths) <= 0 or self.file_index >= len(self.file_paths):
            return

        cur_path = self.file_paths[self.file_index]
        self.process_image(cur_path)

上一个文件

    # 上一个文件
    @pyqtSlot()
    def on_btnFolderPrevious_clicked(self):
        # 文件索引减 1
        self.file_index -= 1
        if self.file_index < 0:
            self.file_index = 0

        if len(self.file_paths) <= 0 or self.file_index >= len(self.file_paths):
            return

        # 当前路径
        cur_path = self.file_paths[self.file_index]
        self.process_image(cur_path)

其它对话框操作

QFileDialog.getExistingDirectory()   # 返回选中的文件夹路径
QFileDialog.getOpenFileName()   # 返回选中的文件路径
QFileDialog.getOpenFileNames()   # 返回选中的多个文件路径
QFileDialog.getSaveFileName()   # 存储文件

大神的路径
对话框操作

猜你喜欢

转载自blog.csdn.net/weixin_45875105/article/details/113185870