gpt4 book ai didi

使用 tkinter 的 Python 多线程

转载 作者:可可西里 更新时间:2023-11-01 11:16:51 27 4
gpt4 key购买 nike

我正在尝试构建一个有点像个人助理的 Tkinter GUI,但是我遇到了第一个障碍 :( 当我更新 GUI 并使用 speech_recognition 收听时,它卡住并说没有响应!我了解我需要使用多线程,但我仍然不知道如何使用它!

这是我的代码和我使用多线程的失败尝试。

import tkinter as tk
from subprocess import call as say
import winsound
import speech_recognition as sr
import threading

def cbc(tex):

return lambda : callback(tex)

def callback(tex):
button = "Listen"

tex.insert(tk.END, button)
tex.see(tk.END)# Scroll if necessary



def listen(tex):
def callback(tex):
g = ("Say,,your,,command,,after,,the,,beep")
say('espeak '+ g, shell = True)

winsound.Beep(1000,500)


ltext = 'listening...'
tex.insert(tk.END, ltext)

r = sr.Recognizer()

with sr.Microphone() as source:
damand = r.listen(source)

damandtxt = (recognizer_google(damand))
tex.insert(tk5.END, damandtxt)

tex.see(tk.END)


t3 = threading.Thread(target = callback(tex))
t3.daemon = True
t3.start()

top = tk.Tk()
tex = tk.Text(master=top)
tex.pack(side=tk.RIGHT)
bop = tk.Frame()
bop.pack(side=tk.LEFT)


tk.Button(bop, text='Listen', command=lambda: listen(tex)).pack()
tk.Button(bop, text='Exit', command=top.destroy).pack()

top.mainloop()

我只需要知道如何正确使用它。请

p.s 我已经阅读了所有文档和关于多线程的所有内容,但它就是行不通:'(

提前谢谢你:)

最佳答案

你错误地调用了你的线程,

 t3 = threading.Thread(target = callback(tex))

callback(tex) 正在调用函数,而不是将其作为目标传入。如果你想以这种方式使用它,你需要使用 target = lambda: callback(tex)

你应该像这样使用线程:

 t3 = threading.Thread(target = callback, args=(tex,))

另外请注意,您真的不需要将该函数嵌套在您的其他函数中,您可以将它移到外面并且它将具有 tex 参数,因为您正在将参数传递给您线程。

关于使用 tkinter 的 Python 多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36583569/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com