首页 > 解决方案 > tkinter 使用语音识别时没有响应

问题描述

所以我使用由一个窗口和一个按钮组成的 tkinter,当我按下监听按钮时它开始没有响应我已经寻找解决方案并且大多说我们必须使用线程但是如何实现它任何人都可以帮助?这是我的代码

import speech_recognition as sr
import tkinter as tk
from tkinter import *

def listen():
    listener = sr.Recognizer()
    try:
        with sr.Microphone() as source:
            print("Listening...")
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            # command = command.lower()
            # if 'bot' in command1:
            #     command1 = command1.replace('bot', '')
            print(command)
    except:
        print("not working")
        pass

def stop():
    pass

form = tk.Tk()
form.geometry('1200x600')
buttonListen = Button(form, text='listen',command=listen)
buttonListen.pack()

form.mainloop()

这是我的代码有人可以帮助我吗?

标签: pythontkinterspeech-recognition

解决方案


您必须创建一个创建线程并运行它的函数。

示例代码:

import speech_recognition as sr
import tkinter as tk
import threading

def listen():
    listener = sr.Recognizer()
    try:
        with sr.Microphone() as source:
            print("Listening...")
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            # command = command.lower()
            # if 'bot' in command1:
            #     command1 = command1.replace('bot', '')
            print(command)
    except:
        print("not working")
        pass

def listen_thread():
    thread = threading.Thread(target= listen)
    thread.start()

form = tk.Tk()
form.geometry('1200x600')
buttonListen = tk.Button(form, text='listen', command=listen_thread)
buttonListen.pack()

form.mainloop()

我运行了一次,输出如下:

Listening...
hello 1 2 3 4 5 6 7 8 9 10

并且不要为同一个模块进行 2 次导入。

使用import tkinter as tk代替from tkinter import *


推荐阅读