【问题标题】:Python multi-threading with tkinter使用 tkinter 的 Python 多线程
【发布时间】:2016-08-03 16:10:10
【问题描述】:

我正在尝试构建一个类似于个人助理的 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 我已经阅读了所有关于多线程的文档和所有内容,但它只是不起作用:'(

提前谢谢你:)

【问题讨论】:

    标签: python windows python-3.x tkinter python-multithreading


    【解决方案1】:

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

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

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

    你应该像这样使用线程:

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

    另外请注意,您确实不需要将该函数嵌套在其他函数中,您可以将其移到外面,因为您将争论传递给您的线程,所以它将具有 tex 争论。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      • 2022-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多