2016-04-12 90 views
1

我試圖建立一個Tkinter的GUI有點像個人助理,但我已經倒在拳頭障礙:(當我更新GUI和偵聽speech_recognition,它會凍結並說沒有響應!我明白,我需要使用多線程但我被困在如何使用它!python多線程與tkinter

這裏是我的代碼和我在使用多線程失敗的嘗試。

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() 

我只需要知道如何正確使用它。請

ps我讀過的所有文件,一切都在多線程,但它只是不工作:「(

預先感謝您:)

回答

4

你打電話你的線程錯誤,

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

callback(tex)正在調用該函數,而不是將其作爲目標傳入。如果你想用這種方式,你需要使用target = lambda: callback(tex)

您應該使用線程這樣的:

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

而且在另一方面,你真的不需要該函數嵌套的內部你其他功能,你可以將它移動到外面,並且它會有你自己的爭論,因爲你將這個爭論傳遞給了你的線程。