Using an LLM to Write a Desktop Tool: Keeping the UI Responsive with Threads and Queues
This article shows how to build a batch audio extraction desktop tool with an LLM, using tkinter and the ffmpeg command-line tool. It explains how to write requirements as checkable specifications, how to keep the interface responsive during conversion with a worker thread and a queue, and which items to verify in generated code. The approach suits small tkinter tools that call an external ffmpeg, not high-concurrency or complex media processing.
This article does not compare the strengths of different models, and it does not provide benchmark scores or timing data. The code in this article runs as written, but first you need to install Python 3 and ffmpeg in your own environment and complete the verification in Section 4. This approach suits small desktop tools built with tkinter and an external ffmpeg command-line call. It does not suit high-concurrency or complex media processing.
1. Writing the Requirements as a Specification
The quality of a model’s output depends heavily on how specific the requirements are. If you only write “build an audio and video conversion tool,” the model will decide most of the details on its own, and the result is hard to predict. A safer approach is to write the requirements the way you would in a requirements document: list every item and attach a way to verify it.
| Requirement | How it is written in the prompt | Acceptance check |
|---|---|---|
| Tech stack | Python 3. The GUI uses the standard library tkinter. Audio extraction calls the ffmpeg command-line tool installed on the system. No third-party GUI library. | Runs with only the standard library and ffmpeg |
| Input | Supports mp4, mkv, mov, and avi. Multiple files can be selected, or a folder can be selected recursively. Non-video files are ignored. | When a folder is selected, videos in its subdirectories are also added to the list |
| Output | mp3 or wav. The output directory is optional and defaults to the directory where the program is located. | Output files appear in the specified directory |
| Interface | File list, format dropdown, output directory button, progress bar, status bar, and start and cancel buttons | All of these controls are present |
| Errors | If ffmpeg is not installed, the status bar shows installation instructions. A failed file does not affect the other files, and the status bar lists the names of failed files. | Deliberately create one failing file. The remaining files still finish converting. |
| Constraints | The UI does not freeze during conversion. Existing files are not overwritten. Original videos are not modified or deleted. | The window can be dragged during conversion. A same-name output is renamed with a _1 suffix. The checksum of the source file does not change. |
Write constraints into the prompt. The model does not follow constraints it was never given. It often leaves them out or falls back on default behavior.
2. Why the Interface Freezes
tkinter and most desktop GUI frameworks rely on a main loop, called mainloop. The main loop handles clicks, redrawing, and window movement. If the conversion runs directly inside a button callback, the main loop waits until the conversion finishes. During that time, the window cannot be dragged, the progress bar does not update, and the cancel button does not respond.
A common fix is to run the slow task in a worker thread and follow two rules:
- The worker thread never modifies widgets directly. It puts progress and status messages into a queue.Queue.
- The main thread uses the after method to read the queue on a timer and then updates the interface.
With this design, widgets are modified only on the main thread, and the slow operation does not block the main loop. tkinter widgets are not designed for cross-thread calls. Modifying them directly from a child thread can cause errors that are hard to reproduce.
The approach has three boundary conditions to note:
- The polling interval is 100 ms. This interval refreshes the interface promptly while using almost no CPU.
- Progress is counted per file and updated each time a file finishes, so updates for batch jobs are naturally infrequent. To show progress within a single file, use ffprobe to read the duration, then parse the out_time_ms field in ffmpeg’s progress output.
- The subprocess output must be read continuously. ffmpeg writes its output to a pipe. If nothing reads the pipe, the buffer fills up, ffmpeg blocks, and the conversion looks frozen. This article merges stderr into stdout and has the worker thread read it line by line to avoid this problem.
3. A Runnable Code Skeleton
Save the following code as extract_audio.py to run it.
```python
import os
import queue
import shutil
import subprocess
import threading
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
VIDEO_EXTS = (“.mp4”, “.mkv”, “.mov”, “.avi”)
CODEC_ARGS = {
“mp3”: [“-vn”, “-c:a”, “libmp3lame”, “-q:a”, “2”],
“wav”: [“-vn”, “-c:a”, “pcm_s16le”],
}
POLL_MS = 100
def uniquepath(out_dir, src, fmt):
“””Generate an output path that does not overwrite an existing file. If the name is taken, append _1, _2, and so on.”””
base = os.path.splitext(os.path.basename(src))[0]
candidate = os.path.join(out_dir, f”{base}.{fmt}”)
n = 1
while os.path.exists(candidate):
candidate = os.path.join(out_dir, f”{base}{n}.{fmt}”)
n += 1
return candidate
def stop_process(proc):
“””Terminate the subprocess and close its output pipe so no leftover process remains.”””
if proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
if proc.stdout:
proc.stdout.close()
def convert_one(ffmpeg, src, dst, fmt, cancel_event):
“””Convert one file. Returns (success, reason). A reason of ‘cancelled’ means the user cancelled.”””
cmd = [ffmpeg, “-n”, “-hide_banner”, “-nostats”, “-loglevel”, “error”,
“-progress”, “pipe:1”, “-i”, src, *CODEC_ARGS[fmt], dst]
proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
encoding=”utf-8”,
errors=”replace”,
creationflags=subprocess.CREATE_NO_WINDOW if os.name == “nt” else 0,
)
messages = []
cancelled = False
rc = None
try:
for line in proc.stdout:
if cancel_event.is_set():
cancelled = True
break
line = line.strip()
if line and “=” not in line:
messages.append(line)
if not cancelled:
rc = proc.wait()
finally:
stop_process(proc)
if cancelled or rc != 0:# dst was chosen by unique_path and did not exist at that point, so any file here was created by this task.if os.path.exists(dst):os.remove(dst)if cancelled:return False, "cancelled"if rc != 0:return False, messages[-1] if messages else f"返回码{rc}"return True, ""
class Worker(threading.Thread):
def init(self, ffmpeg, files, outdir, fmt, msgqueue, cancel_event):
super().__init(daemon=True)
self.ffmpeg = ffmpeg
self.files = files
self.out_dir = out_dir
self.fmt = fmt
self.msg_queue = msg_queue
self.cancel_event = cancel_event
def emit(self, kind, payload):self.msg_queue.put((kind, payload))def run(self):total = len(self.files)failed = []for i, src in enumerate(self.files, 1):if self.cancel_event.is_set():breakname = os.path.basename(src)self
