首页 > 解决方案 > 当 Speech_recognition 在按钮单击时运行时 UI 冻结

问题描述

我创建了一个 python 文件,当单击开始时,麦克风应该工作并开始说话,如果我停止它应该将语音转换为文本并将其添加到文本框中,但每次我单击开始时应用程序崩溃了!

import tkinter as tk
import speech_recognition as sr


window = tk.Tk()
window.title("Voice to Text")
window.geometry("300x300")


def startvoice():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        try:
            audio = r.record(source)
            voice2text = r.recognize_google(audio)
            text_field.focus()
            text_field.delete()
            text_field.insert(0, voice2text)
        except:
            print("error")


button1 = tk.Button(text="Start", width=16, command=startvoice)
button1.grid(column=0, row=0)

text_field = tk.Text(master=window, height=20, width=40)
text_field.grid(column=0, row=1)


window.mainloop()

标签: pythontkinteronclickspeech-recognitionspeech-to-text

解决方案


您需要r.record(source)在单独的线程中运行及以下。


推荐阅读