python - 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()
这是我的代码有人可以帮助我吗?
解决方案
您必须创建一个创建线程并运行它的函数。
示例代码:
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 *
推荐阅读
- swift - 如果初始窗口没有标题栏,如何关闭它
- mysql - 连接mysql中的两个表,其中一个值对应另一个表中的两个值
- java - 在 Selenium 中使用 Gmail API 无法正常获取电子邮件主题
- python - 在 macOS [python, PySimpleGUI, Tkinter, macOS] 中通过 tkinter 非常慢的窗口刷新(更新)
- apache - Apache 反向代理背后的 Radarr 问题
- azure - Azure Lighthouse 入职客户不在客户列表中
- ruby-on-rails - Rails 延迟的工作给出了禁止的错误?
- simulation - 如何计算边界上的拉普拉斯模板?
- image - 如何在从 QuPath 同时导出多个注释时添加注释标签?
- sybase - 如何在数据夹中使用打印