在分配之前定义“变量”

时间:2019-10-12 13:46:59

标签: python qml pyqt5

我正尝试使用语音识别器pyqt5 qml和gtts制作VA。但是每次我运行此命令时,我都会收到错误消息,指出作业之前已定义了speek。我不能添加myCommand(any_other defenition)或myCommand(),因为这不是pyqt5的定义,我该怎么办。

import sys
from PyQt5.QtCore import QObject, QUrl
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQuick import QQuickView
from PyQt5.QtQml import QQmlApplicationEngine
import os
import speech_recognition as sr
from gtts import gTTS
def myCommand():
    say1.setProperty("text", "say something")
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print('Ready...')
        audio = r.listen(source)
    try:
        command = r.recognize_google(audio, language = 'ml-IN')
        print (command)
    except sr.UnknownValueError:
        print('Your last command couldn\'t be heard')
    if command != '':
        command1.setProperty("text", command)
        if 'ലൈറ്റ്' in command:
            if 'ഓണ്‍' in command:
                speek = 'ശരി'
    print(speek)

if __name__ == '__main__':
    myApp = QApplication(sys.argv)

    engine = QQmlApplicationEngine()
    context = engine.rootContext()
    context.setContextProperty("main", engine)

    engine.load('main.qml')
    engine.load('steve.qml')

    win = engine.rootObjects()[0]
    commander = win.findChild(QObject, "commander")
    say1 = win.findChild(QObject, "say")
    command1 = win.findChild(QObject, "command")
    editText = win.findChild(QObject, "editText")
    animation = win.findChild(QObject, "animation")
    scaler = win.findChild(QObject, "scaler")
    rotator = win.findChild(QObject, "rotator")


    commander.clicked.connect(myCommand)
    win.show()

    sys.exit(myApp.exec_())

1 个答案:

答案 0 :(得分:1)

您需要在函数print(speek)中缩进myCommand()命令。

if command != '':
    command1.setProperty("text", command)
    if 'ലൈറ്റ്' in command:
        if 'ഓണ്‍' in command:
            speek = 'ശരി'
            print(speek)

引发此错误是因为在speek块中定义了if,并且在某些情况下if的求值结果不是True,而speek的求值结果却不是可访问的。

您可能会发现this interesting