Question Details

No question body available.

Tags

python multithreading tkinter speech-recognition vosk

Answers (1)

March 15, 2026 Score: 3 Rep: 3,561 Quality: Medium Completeness: 80%

The while True: loop prevents the tkinter's mainloop from running (that is, the process does not reach the mainloop call), since the main code runs sequentially.

One can use the threading Python module to move the voice recognition part in another thread like so:

import tkinter as tk
from vosk import Model, KaldiRecognizer
import pyaudio
import json
import threading # Added import.

Reads audio, recognizes text, and updates the label:

def listen(recognizer, stream, label): while True: data = stream.read(4000) if rec.AcceptWaveform(data): result = json.loads(rec.Result()) text = result["text"] label.config(text=text)

model = Model("vosk-model-small-cn-0.22") rec = KaldiRecognizer(model, 16000)

p = pyaudio.PyAudio() stream = p.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True, framesperbuffer=8000)

root = tk.Tk() label = tk.Label(root, text="Speech result") label.pack()

Create and start the thread which performs voice recognition:

t = threading.Thread( target=listen, kwargs=dict(recognizer=rec, stream=stream, label=label) ) t.daemon = True # When the user closes the tkinter's window then the thread will not prevent the end of the process. t.start()

root.mainloop()

According to tkinter's Threading model:

Calls to tkinter can be made from any Python thread. Internally, if a call comes from a thread other than the one that created the Tk object, an event is posted to the interpreter’s event queue, and when executed, the result is returned to the calling Python thread.

... so it is safe to update the label from another thread.


Another option is to move the mainloop itself in another thread. In case mainloop can run on a different thread than the one that created the root, then to move mainloop on another thread would be as simle as replacing root.mainloop() with:

threading.Thread(target=root.mainloop).start()

But since I cannot find this information explicitly stated at the moment, one can refer to other similar posts such as Multithreading: tkinter mainloop not in main thread for moving the mainloop in another thread.


Note, above code does not properly handle releasing resources. That's because ending mainloop ends the process, so the stream is released (since the process terminates). But, in bigger applications, one would most likely need to properly release the stream when no longer needed.