Python &引用;变量";是在分配之前定义的

Python &引用;变量";是在分配之前定义的,python,qml,pyqt5,Python,Qml,Pyqt5,我试着用语音识别器pyqt5 qml和gtts进行语音识别。但每次我运行这个程序,我都会得到一个错误,上面写着speek在赋值之前定义的。我不能添加myCommand(任何其他防御)或myCommand(),因为这是为pyqt5未定义的,我该怎么做 import sys from PyQt5.QtCore import QObject, QUrl from PyQt5.QtWidgets import QApplication from PyQt5.QtQuick import QQuickVi

我试着用语音识别器pyqt5 qml和gtts进行语音识别。但每次我运行这个程序,我都会得到一个错误,上面写着speek在赋值之前定义的。我不能添加myCommand(任何其他防御)或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_())

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

引发此错误的原因是
speek
if
块中定义,并且在
if
未计算为
True
的情况下,
speek
无法访问

你可能会发现

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