我正在使用tkinter和google speech to text library用python创建gui语音助手。占位符是文本将来的位置。
我遇到的问题是,在按下麦克风按钮并再次单击它之后,会出现一个错误 RuntimeError: threads can only be started once
即使在听力过程结束之后。
gui类代码:
def __init__(self):
self.root = Tk()
self.root.title("HireBot")
self.root.iconbitmap("icon.ico")
# To say how big the window should be initially
self.root.geometry("320x600") # wxh
self.root.configure(bg='pink')
self.logo = ImageTk.PhotoImage(Image.open("icon_deactivated.png"))
self.logo1 = ImageTk.PhotoImage(Image.open("icon_activated.png"))
self.l = Label(image=self.logo, borderwidth=0, width=1000, anchor="center", bg="pink")
self.l.pack()
self.welcome = Label(text="Welcome! How may I help you today? \n Ask 'what can you do' to know what I can do", borderwidth=0, anchor="center", pady=5, fg="blue", bg="pink", font="arial").pack()
self.frame = LabelFrame(self.root, padx=5, pady=5) # pads inside the frame
self.frame.pack(padx=10, pady=10) # To pad from the outside
# To put things in frames
hold = Label(self.frame, text="Placeholder").pack()
# Mic button
self.button_on = ImageTk.PhotoImage(Image.open("MicOn.png").resize((50, 50), Image.ANTIALIAS))
self.button_off = ImageTk.PhotoImage(Image.open("MicOff.png").resize((50, 50), Image.ANTIALIAS))
#self.t = Thread(target=self.get_audio, args=("new", None))
#self.t.setDaemon(True)
self.mic = Button(self.root, image=self.button_on, border=0, bg="pink", command=threading.Thread(target=self.get_audio).start)
self.mic.pack()
self.pressed = True
代码的其余部分
def run(self):
self.root.mainloop()
def get_audio(self):
if self.pressed:
self.mic.config(image=self.button_off)
self.pressed = False
# First create recogniser object
r = sr.Recognizer()
# Use microphone to get input
with sr.Microphone() as source:
audio = r.listen(source) # Use speech recogniser to listen to source(microphone)
# What user said
said = ""
try:
said = r.recognize_google(audio) # Uses google API to recognise what user said
print(said)
except Exception as e:
print("Exception: " + str(e))
self.mic.config(image=self.button_on)
return said
else:
self.mic.config(image=self.button_on)
self.pressed = True
print(self.pressed)
a = GUI()
a.run()
如何终止线程,以便根据需要多次单击按钮?
暂无答案!
目前还没有任何答案,快来回答吧!