使用按钮创建目录

问题描述 投票:0回答:1

当我按下按钮时,新文件夹就会创建,但只有在我关闭应用程序之后才会创建。

这是我打开一个窗口的方法,我可以在其中选择图像。接下来,我将图像转换为灰度并尝试将灰度图像保存到新文件夹。

代码:

    def getFile(self):
        #Open window to choose file
        self.filePath, _ = QFileDialog.getOpenFileNames(self.window, 'Choose an image', "${HOME}","Formats: (*.png )")

        for filePath in self.filePath:
            image = Image.open(filePath)
            #convert image to greyscale
            img_grey = image.convert('L')

            filename = os.path.basename(filePath)
            #make new folder
            os.makedirs(self.output_dir, exist_ok=True)
            #join a filname from original image to image after greyscale
            output_path = os.path.join(self.output_dir, filename)
            #save a greyscale image to new folder
            img_grey.save(output_path)

output_dir我在definit中定义(我创建的方法):

class Ui_MainWindow(object):


    def __init__(self):

        self.filePath = ''
        self.currentDir = os.getcwd()
        self.images = []
        self.output_dir = os.path.abspath('..\\greyscale_images')

应用程序运行时是否可以创建新文件夹?如果是这样,我该怎么办? 我是Python新手。如果您需要更多信息,请写信。

python-3.x directory pyqt5 save grayscale
1个回答
0
投票
import os
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QPushButton
from PIL import Image

class Ui_MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Image Converter")
        self.setGeometry(100, 100, 200, 100)

        button = QPushButton('Choose Image', self)
        button.clicked.connect(self.getFile)
        button.resize(200, 100)
        button.move(0, 0)

        self.filePath = ''
        self.output_dir = os.path.join(os.getcwd(), 'greyscale_images')

    def getFile(self):
        # Open window to choose file
        filePath, _ = QFileDialog.getOpenFileName(self, 'Choose an image', os.getenv("HOME"), "Images (*.png *.jpg *.jpeg)")
        if filePath:
            self.convertToGreyscale(filePath)

    def convertToGreyscale(self, filePath):
        # Load image
        image = Image.open(filePath)
        img_grey = image.convert('L')

        # Create output directory
        os.makedirs(self.output_dir, exist_ok=True)

        # Prepare output file path
        filename = os.path.basename(filePath)
        output_path = os.path.join(self.output_dir, 'greyscale_' + filename)

        # Save the greyscale image
        img_grey.save(output_path)
        print(f"Image saved to {output_path}")

def main():
    app = QApplication(sys.argv)
    mainWindow = Ui_MainWindow()
    mainWindow.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

© www.soinside.com 2019 - 2024. All rights reserved.