You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyQt仪表板开发:按QLineEdit命名创建文件夹并存储图片

PyQt仪表板图片保存功能实现

功能需求

  • 通过Browse按钮打开文件对话框选择图片,QLineEdit输入人员姓名和ID
  • 首次输入该姓名时,自动创建以姓名命名的文件夹,并将选中图片存入
  • 若同名文件夹已存在,直接将选中图片添加至该文件夹

现有尝试代码

界面初始化代码

def person_Details(self):
    self.add_area.setStyleSheet('background-color:white')
    self.v_parent_layout = QVBoxLayout()
    self.v_layout = QVBoxLayout()
    self.H_layout = QHBoxLayout()
    # 表单布局
    self.q_form = QFormLayout()
    self.q_form_box = QGroupBox("Enter Your Details")
    self.nameLineEdit = QLineEdit()
    self.IDLineEdit = QLineEdit()
    self.q_form.addRow(QLabel("Name"), self.nameLineEdit)
    self.q_form.addRow(QLabel("ID"), self.IDLineEdit)
    self.q_form_box.setLayout(self.q_form)
    self.v_layout.addWidget(self.q_form_box)
    # 按钮布局
    self.save = QPushButton("SAVE")
    self.Browse = QPushButton("BROWSE")
    self.Browse.clicked.connect(self.getImage)
    self.save.clicked.connect(self.show_entries)
    self.checkbox = QCheckBox("CHECK", self)
    self.H_layout.addWidget(self.save)
    self.H_layout.addWidget(self.Browse)
    self.H_layout.addWidget(self.checkbox)
    self.checkbox.stateChanged.connect(self.clickBox)
    # 组合布局
    self.v_parent_layout.addLayout(self.v_layout)
    self.v_parent_layout.addLayout(self.H_layout)
    self.add_area.setLayout(self.v_parent_layout)

图片选择代码

def getImage(self):
    import os
    self.fname = QFileDialog.getOpenFileNames(self, 'Open file', os.getcwd(), "Image files (*.jpg *.gif *.jpeg)")
    try:
        # 取第一张图片预览
        imagePath = self.fname[0][0]
        pixmap = QPixmap(imagePath)
        self.pic_1.setPixmap(pixmap)
        self.pic_2.setPixmap(pixmap)
        self.pic_3.setPixmap(pixmap)
        self.pic_4.setPixmap(pixmap)
        self.resize(pixmap.width(), pixmap.height())
    except IndexError as e:
        print(e)

文件夹创建与图片保存测试代码

from PIL import Image
import os
from CONSTANT import *

name_of_folder = "some_name"
absolute_path = os.path.join(path, name_of_folder)
if not os.path.exists(absolute_path):
    os.makedirs(absolute_path)
image = Image.open("/home/Downloads/image_1.jpg")
image.save(f"{absolute_path}/{name_of_folder}.jpg")

解决方案

将文件夹创建和图片保存逻辑整合到save按钮的槽函数中,同时处理多图选择和文件名重复问题:

修改后的关键代码

import os
import shutil
from PIL import Image
from PyQt5.QtWidgets import *

# 类初始化时添加选中图片列表
def __init__(self):
    # 其他初始化代码...
    self.selected_images = []

def getImage(self):
    self.selected_images, _ = QFileDialog.getOpenFileNames(self, '选择图片', os.getcwd(), "Image files (*.jpg *.gif *.jpeg)")
    if self.selected_images:
        # 预览第一张图片
        imagePath = self.selected_images[0]
        pixmap = QPixmap(imagePath)
        self.pic_1.setPixmap(pixmap)
        self.pic_2.setPixmap(pixmap)
        self.pic_3.setPixmap(pixmap)
        self.pic_4.setPixmap(pixmap)
        self.resize(pixmap.width(), pixmap.height())

def save_images_to_folder(self):
    # 获取输入姓名并校验
    name = self.nameLineEdit.text().strip()
    if not name:
        QMessageBox.warning(self, "提示", "请输入姓名")
        return
    if not self.selected_images:
        QMessageBox.warning(self, "提示", "请先选择图片")
        return
    
    # 拼接目标文件夹路径(替换为你的实际根目录)
    from CONSTANT import path
    folder_path = os.path.join(path, name)
    
    # 创建文件夹(已存在则自动跳过)
    os.makedirs(folder_path, exist_ok=True)
    
    # 遍历保存选中的图片,避免文件名重复
    for img_path in self.selected_images:
        img_name = os.path.basename(img_path)
        target_path = os.path.join(folder_path, img_name)
        
        # 文件名重复时添加序号
        counter = 1
        while os.path.exists(target_path):
            name_part, ext_part = os.path.splitext(img_name)
            target_path = os.path.join(folder_path, f"{name_part}_{counter}{ext_part}")
            counter += 1
        
        # 方式1:直接复制文件(保留原文件属性)
        shutil.copy2(img_path, target_path)
        
        # 方式2:用PIL保存(适合需要编辑图片的场景)
        # image = Image.open(img_path)
        # image.save(target_path)
    
    QMessageBox.information(self, "成功", "图片已保存")

# 修改person_Details中的save按钮连接
def person_Details(self):
    # ... 原有代码 ...
    self.save.clicked.connect(self.save_images_to_folder)
    # ... 原有代码 ...

核心说明

  1. 多图支持:在getImage中保存所有选中的图片路径,支持批量选择
  2. 简洁创建文件夹:用os.makedirs(..., exist_ok=True)替代手动判断,代码更简洁且避免竞态问题
  3. 文件名防重复:自动为重复文件名添加序号,防止覆盖已有图片
  4. 用户校验:添加空值校验,确保姓名和图片选择完成后再执行保存
  5. 两种保存方式:直接复制保留原文件属性,PIL保存适合需要压缩、格式转换等场景

内容的提问来源于stack exchange,提问作者parth percy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 16:10:29