PYQT文件转换器在gui中。按钮不与转换器一起使用

时间:2015-09-14 17:11:09

标签: python pyqt

我正在尝试制作一个GUI文件转换器,并能够使用终端和我的脚本转换文件,但现在尝试使用几个按钮启用它。到目前为止,GUI将获取目录,附加到列表,但是当我点击转换按钮时,它们不会在脚本中使用。

def convertor():
    # process all non-master CSVs
    for fileLocated in os.listdir(directoryPath):
        if fileLocated.endswith(".csv") and 'master' not in fileLocated.lower():

            csvFilename = fileLocated
            strippedFileName =  os.path.splitext(csvFilename)[0]
            wavFileName =  directoryPath  + strippedFileName + ".wav"

            print strippedFileName
            cutOff = re.compile(r"(([0-9]{8})?.*_[Tt]r-[0-9]+)_?(?:([0-9]+)mph)?.*")
            allGroups = cutOff.search(strippedFileName).groups()
            result = cutOff.search(strippedFileName)
            xmlBaseFileName = result.group(1)
            if result.group(2) is not None: # try to get date of delivery from filename
                dateDelivery = "%s/%s/%s" % (result.group(2)[0:2], result.group(2)[2:4], result.group(2)[4:8])
            else:
                dateDelivery = 'n/a'
                print 'Could not parse date received from filename'
            if result.group(3) is not None: # try to get mph from filename
                mph = result.group(3)
            else:
                mph = 'n/a/'
                print 'Could not parse mph from filename'

            csvFilename = directoryPath + csvFilename
            csvFile = open(csvFilename, 'rU')

            csvReader = csv.DictReader(csvFile, delimiter=',', quotechar='"')

            postProcTags = ["startTime", "endTime", "transcription", "signalQuality", "startSession", "endSession"]

            metaDataObj = metaDataCreator.MetaData()

            for row in csvReader:
                sampleNode = etree.Element("Sample")
                if "literalPrompt" in row and row["literalPrompt"].strip() != '':
                    promptNode = etree.Element("Prompt")
                    promptNode = metaDataCreator.createPromptNode(*[(tagName, row[tagName]) for tagName in row.keys() if tagName not in postProcTags and tagName != 'order'])
                    sampleNode.append(promptNode)
                if "transcription" in row and row["transcription"].strip() != '':

                    postProcNode = etree.Element("postProc")
                    postProcNode = metaDataCreator.createPostProcNode(*[row[postProcTag] for postProcTag in postProcTags])
                    sampleNode.append(postProcNode)

                metaDataObj.addSamplePair(sampleNode)

                    #print etree.tostring(sampleNode, pretty_print=True)

            metaDataObj.createSpeakerNode(gender="Male") # (speakerId='80', gender="Female", ageGroupMin="40", ageGroupMax="49", nativeSpeaker="True")
            metaDataObj.createAudioNode(filePath=wavFileName)
            metaDataObj.createSessionNode(speed=mph, subDomain='biking')
            metaDataObj.createGeneralNode(originalFileName=xmlBaseFileName, dateOfDelivery=dateDelivery, dateOfProcessing='%s/%s/%s' % (date.today().month, date.today().day, date.today().year))
            metaDataObj.createHardwareSetupNode(micType='n/a', bikeUnit='311', micAngle='n/a')






            tree = etree.ElementTree(metaDataObj.root)
            outputFilename = csvFilename.replace(".csv", ".xml")

            tree.write(outputFilename, pretty_print=True)

等。

然后..

class pageTwo(QtGui.QDialog):
    def __init__(self,parent = None):
        QtGui.QDialog.__init__(self, parent)

        self.initUI()

    def initUI(self):

        self.setGeometry(300,300,800,600)
        self.setWindowTitle("Convertor")
        self.setStyleSheet("font-size:15px")

        self.buttonConvert = QtGui.QPushButton('Convert!', self)
        self.buttonConvert.move(350, 350)
        self.buttonConvert.clicked.connect(self.convert)

        self.buttonSelect = QtGui.QPushButton('Select Files', self)
        self.buttonSelect.move(135, 200)
        self.buttonSelect.clicked.connect(self.get_in_filename)


    def get_in_filename(self):
        """Ask user for the input filename."""
        self.listWidget.clear()
        directory = QtGui.QFileDialog.getExistingDirectory(self,
                                                           "Pick a folder")

        if directory:
            for file_name in os.listdir(directory): 
                self.listWidget.addItem(file_name)  



    def get_out_filename(self):
        pass



    def convert(self, directory):
        global convertor
        """Execute the conversion."""

        for file_name in os.listdir(directory):
            if os.listdir(directory):

                convertor(file_name)
                self.listWidgetcomplete.addItem(file_name)

我知道我可能在这里发布了太多代码:(任何帮助都将不胜感激!

1 个答案:

答案 0 :(得分:0)

您的转换函数有一个参数directory,它指定要操作的目录。但是你通过以下方式调用转换函数:

   self.buttonConvert.clicked.connect(self.convert)

clicked信号传递参数。但它是一个布尔值。所以你试图“转换”真或假,而不是你想要的目录。这引发了异常,但PyQt信号槽机制正在吞噬异常。

您需要找到另一种方法将目录转换为转换槽。例如,convert可以从成员变量中读取它。或列表小部件。