joe woodger
joe woodger

Reputation: 49

Python multi-threading with tkinter

I'm trying to build a Tkinter GUI that is sort of like a personal assistant, however I've fallen at the fist hurdle :( When I update the GUI and listen with speech_recognition, it freezes and says not responding! I understand that I need to use multi threading however I'm stuck on how to use it!

Here's my code and my failed attempt at using multi-threading.

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

I just need to know how to use it correctly. Please

p.s I've read all the documentation and everything on multi-threading but it just doesn't work :'(

Thank you in advance :)

Upvotes: 1

Views: 478

Answers (1)

Pythonista
Pythonista

Reputation: 11645

You're calling your thread incorrectly,

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

callback(tex) is calling the function, instead of passing it in as the target. If you want to use it this way you need to use target = lambda: callback(tex)

You should be using the thread like this:

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

Also on another note, you really don't need that function nested inside of your other function, you can move it outside and it will have the tex arguement since you are passing the arguement to your thread.

Upvotes: 4

Related Questions