【问题标题】:tkinter not responding when using speech recogmitiontkinter 使用语音识别时没有响应
【发布时间】:2021-09-06 15:48:37
【问题描述】:

所以我使用由一个窗口和一个按钮组成的 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()

这是我的代码,谁能帮帮我?

【问题讨论】:

    标签: python tkinter speech-recognition


    【解决方案1】:

    你必须创建一个函数来创建一个线程并运行它。

    示例代码:

    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 *

    【讨论】:

    • 非常感谢
    猜你喜欢
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 2019-06-19
    • 2014-12-30
    • 1970-01-01
    • 2018-02-23
    • 2011-11-16
    • 1970-01-01
    相关资源
    最近更新 更多