Порядок выполнения button.clicked.connect()
Пишу на питоне голосового помощника.
Есть код второй части - когда я запускаю код и нажимаю кнопку,
код должен сначала поменять картинку в self.label = QLabel()
,
а потом начать записывать голос и переводить его в текст.
Но, почему-то, картинка меняется только после записи голоса и перевода его в текст?
self.pixmap1 = QPixmap('слушает_нач_вариант.jpg')
self.label.setPixmap(self.pixmap1)
выполняется последним.
Можете подсказать, почему, и как это исправить?
main.py:
import time
import speech_recognition as sr
from threading import Thread
from PyQt6.QtWidgets import QApplication, QGraphicsPixmapItem, QWidget, QMainWindow, QPushButton, QLabel, QVBoxLayout
from PyQt6.QtGui import QPixmap
import sys
from ain2 import the_button_was_clicked1
recognizer = sr.Recognizer()
microphone = sr.Microphone()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Main Window")
self.setFixedSize(645, 500)
self.layout = QVBoxLayout()
self.label = QLabel()
self.pixmap = QPixmap('говорит.jpg')
self.label.setPixmap(self.pixmap)
self.layout.addWidget(self.label)
self.button = QPushButton("Press Me!")
self.button.setCheckable(True)
# self.button.clicked.connect(self.govor)
self.button.clicked.connect(self.the_button_was_clicked2)
self.button.clicked.connect(self.the_button_was_clicked1)
self.layout.addWidget(self.button)
self.widget = QWidget()
self.widget.setLayout(self.layout)
self.setCentralWidget(self.widget)
def the_button_was_clicked2(self):
self.pixmap1 = QPixmap('слушает_нач_вариант.jpg')
self.label.setPixmap(self.pixmap1)
print('dssgg')
#self.button = QPushButton("Press")
def the_button_was_clicked1(self):
print('click')
recognized_data = ""
with microphone:
# регулирование уровня окружающего шума
recognizer.adjust_for_ambient_noise(microphone, duration=2)
try:
print("Listening...")
audio = recognizer.listen(microphone)
except sr.WaitTimeoutError:
print("Can you check if your microphone is on, please?")
return
# использование online-распознавания через Google
try:
print("Started recognition...")
recognized_data = recognizer.recognize_google(audio, language="ru").lower()
except sr.UnknownValueError:
pass
# в случае проблем с доступом в Интернет происходит выброс ошибки
except sr.RequestError:
print("Check your Internet Connection, please")
print(recognized_data)
def application_setup():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()
return
if True:
application_setup()
Ответы (1 шт):
Автор решения: S. Nick
→ Ссылка
В графическом интерфейсе, действия требующие длительного решения, выполняются в дополнительном потоке.
Выглядит это примерно так:
import sys
#? import time
import speech_recognition as sr
#? from threading import Thread
'''
from PyQt6.QtWidgets import QApplication, QGraphicsPixmapItem, \
QWidget, QMainWindow, QPushButton, QLabel, QVBoxLayout
from PyQt6.QtGui import QPixmap
'''
from PyQt5.Qt import *
#? from ain2 import the_button_was_clicked1
class SpeechRecognitionThread(QThread):
about_text = pyqtSignal(str)
language = "en-US"
def run(self):
try:
r = sr.Recognizer()
self.about_text.emit("Скажите что-нибудь...")
with sr.Microphone() as source:
audio = r.listen(source)
self.about_text.emit("Анализирую речь...")
text = r.recognize_google(audio, language=self.language)
self.about_text.emit('Фраза: "{}"'.format(text))
except sr.UnknownValueError:
self.about_text.emit("Робот не расслышал фразу")
except sr.RequestError as e:
self.about_text.emit("Ошибка сервиса: {}".format(e))
except Exception as e:
self.about_text.emit("Ошибка: {}".format(e))
finally:
self.about_text.emit('')
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.widget = QWidget()
self.setCentralWidget(self.widget)
self.pixmap1 = QPixmap('img/2.jpg')
self.label = QLabel()
self.pixmap = QPixmap('img/1.jpg')
self.label.setPixmap(self.pixmap)
self._label = QLabel(
'Нажмите кнопку SPEAK <br>и скажите что-нибудь.')
self._label.setStyleSheet(
"QLabel{color: white; font: 14pt}")
layout = QHBoxLayout(self.label)
layout.addWidget(self._label,
alignment=Qt.AlignHCenter | Qt.AlignBottom)
self.cb_lang = QComboBox()
self.cb_lang.addItems(["en-US", "ru-RU"])
self.cb_lang.setCurrentIndex(1)
self.button = QPushButton("? SPEAK")
self.button.setFont(QFont('Arial', 16))
self.button.setCheckable(True)
# self.button.clicked.connect(self.the_button_was_clicked2)
# self.button.clicked.connect(self.the_button_was_clicked1)
# !!! +++
self.button.clicked.connect(self._speech_recognition_start)
self.pte_result = QPlainTextEdit()
self.pte_result.setFont(QFont('Arial', 12))
self.pte_result.setReadOnly(True)
self.layout = QVBoxLayout(self.widget)
self.layout.addWidget(self.label)
self.layout.addWidget(self.cb_lang)
self.layout.addWidget(self.button)
self.layout.addWidget(self.pte_result)
# !!! +++
self.thread = SpeechRecognitionThread()
self.thread.about_text.connect(self._about_text)
self.thread.finished.connect(self._speech_recognition_finish)
def _about_text(self, text):
self.pte_result.appendPlainText(text)
self._label.setText(text)
def _speech_recognition_start(self):
self.button.setEnabled(False)
self.pte_result.clear()
self.label.setPixmap(self.pixmap1)
self.thread.language = self.cb_lang.currentText()
self.thread.start()
def _speech_recognition_finish(self):
self.button.setEnabled(True)
self.label.setPixmap(self.pixmap)
self._label.setText(
'Нажмите кнопку SPEAK <br>и скажите что-нибудь.')
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.setWindowTitle("Main Window")
#? window.setFixedSize(645, 500)
window.show()
sys.exit(app.exec())