“变量”在分配之前定义[关闭]
Posted
技术标签:
【中文标题】“变量”在分配之前定义[关闭]【英文标题】:"variable" is defined before assignment [closed] 【发布时间】:2019-10-12 13:46:59 【问题描述】:我试图使用语音识别器 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】:您需要在函数myCommand()
中缩进print(speek)
命令。
if command != '':
command1.setProperty("text", command)
if 'ലൈറ്റ്' in command:
if 'ഓണ്' in command:
speek = 'ശരി'
print(speek)
引发此错误是因为speek
是在if
块中定义的,并且在if
不计算为True
的情况下,speek
不可访问。
你可能会找到this interesting
【讨论】:
以上是关于“变量”在分配之前定义[关闭]的主要内容,如果未能解决你的问题,请参考以下文章