DEV Community

Mate Technologies
Mate Technologies

Posted on

๐Ÿง  Building a Text Emotion Detector GUI in Python (TEXT2EMO)

In this tutorial, weโ€™ll build TEXT2EMO, a desktop application that analyzes text and detects the dominant emotion using Python.

Weโ€™ll use:

Tkinter for the GUI

ttkbootstrap for modern styling

Threading to keep the UI responsive

No machine learning required โ€” perfect for beginners ๐Ÿš€

๐Ÿ“ฆ Step 1: Install Required Libraries

First, make sure Python is installed (3.9+ recommended).

Install ttkbootstrap:

pip install ttkbootstrap
Enter fullscreen mode Exit fullscreen mode

Tkinter comes bundled with Python, so no extra install is needed.

๐Ÿ“ Step 2: Import Dependencies

We start by importing all required modules.

import tkinter as tk
from tkinter import messagebox
import ttkbootstrap as tb
from ttkbootstrap.widgets.scrolled import ScrolledText
import threading
import os
import sys
import time
Enter fullscreen mode Exit fullscreen mode

Why these?

tkinter: base GUI framework

ttkbootstrap: modern UI themes

ScrolledText: text box with scrollbars

threading: prevents UI freezing

time: simulate processing delay

๐Ÿงฐ Step 3: Handle Resource Paths (Optional but Important)

This helper function allows your app to work both normally and when packaged with tools like PyInstaller.

def resource_path(file_name):
    base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_path, file_name)
Enter fullscreen mode Exit fullscreen mode

๐ŸชŸ Step 4: Create the Main Application Window

Now we create the main app window using ttkbootstrap.

app = tb.Window(
    title="TEXT2EMO โ€“ Text Emotion Detection",
    themename="superhero",
    size=(1100, 600)
)
Enter fullscreen mode Exit fullscreen mode

We also configure the grid layout:

app.grid_columnconfigure(0, weight=1)
app.grid_columnconfigure(1, weight=2)
app.grid_rowconfigure(0, weight=1)
Enter fullscreen mode Exit fullscreen mode

This allows the UI to resize properly.

๐Ÿงต Step 5: Thread Control

We use a threading.Event to control stopping processes.

stop_event = threading.Event()
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”ง Step 6: UI Helper Functions

These helpers ensure UI updates happen safely.

def ui(func, *args, **kwargs):
    app.after(0, lambda: func(*args, **kwargs))
Enter fullscreen mode Exit fullscreen mode

Popup helpers:

def show_error(title, msg):
    messagebox.showerror(title, msg)

def show_info(title, msg):
    messagebox.showinfo(title, msg)
Enter fullscreen mode Exit fullscreen mode

Logging helper:

def log_line(text):
    def _log():
        log.text.config(state="normal")
        log.text.insert("end", text + "\n")
        log.text.see("end")
        log.text.config(state="disabled")
    ui(_log)
Enter fullscreen mode Exit fullscreen mode

๐Ÿงฑ Step 7: Create Main Panels

We split the window into left and right panels.

left_panel = tb.Frame(app)
left_panel.grid(row=0, column=0, sticky="nsew", padx=10, pady=10)

right_panel = tb.Frame(app)
right_panel.grid(row=0, column=1, sticky="nsew", padx=10, pady=10)
Enter fullscreen mode Exit fullscreen mode

โœ๏ธ Step 8: Text Input Area

This is where users enter text to analyze.

input_card = tb.Labelframe(left_panel, text="Text Input", padding=15)
input_card.grid(sticky="nsew", pady=5)

text_input = ScrolledText(input_card, height=10)
text_input.grid(sticky="nsew")
Enter fullscreen mode Exit fullscreen mode

โš™๏ธ Step 9: Detection Settings

We add a checkbox to toggle confidence scores.

confidence_mode = tk.BooleanVar(value=True)

tb.Checkbutton(
    settings_card,
    text="Show Confidence Score",
    variable=confidence_mode,
    bootstyle="success"
).pack(anchor="w")
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“Š Step 10: Live Output Log

This panel shows real-time results.

log_card = tb.Labelframe(right_panel, text="Live Output", padding=15)
log_card.grid(sticky="nsew")

log = ScrolledText(log_card)
log.grid(sticky="nsew")
log.text.config(state="disabled")
Enter fullscreen mode Exit fullscreen mode

โณ Step 11: Progress Bar

Visual feedback during processing.

progress = tb.Progressbar(bottom_bar)
progress.grid(sticky="ew", pady=5)
Enter fullscreen mode Exit fullscreen mode

๐Ÿง  Step 12: Emotion Detection Engine

We define emotion keywords using a dictionary.

EMOTIONS = {
    "happy": ["happy", "great", "awesome", "love", "amazing", "good"],
    "sad": ["sad", "down", "depressed", "unhappy", "cry"],
    "angry": ["angry", "mad", "furious", "annoyed"],
    "fear": ["scared", "afraid", "fear", "terrified"],
    "surprise": ["surprised", "shocked", "wow"],
    "neutral": []
}
Enter fullscreen mode Exit fullscreen mode

Detection logic:

def detect_emotion(text):
    text = text.lower()
    scores = {}

    for emo, words in EMOTIONS.items():
        scores[emo] = sum(word in text for word in words)

    emotion = max(scores, key=scores.get)
    confidence = scores[emotion] / max(1, sum(scores.values()))

    return emotion.capitalize(), round(confidence * 100, 2)
Enter fullscreen mode Exit fullscreen mode

โ–ถ๏ธ Step 13: Analyze Text Function

This function runs in a background thread.

def analyze_text():
    content = text_input.text.get("1.0", "end").strip()

    if not content:
        ui(show_error, "Missing Input", "Please enter text to analyze.")
        return
Enter fullscreen mode Exit fullscreen mode

Progress updates and logging:

ui(progress.configure, value=40)
emotion, confidence = detect_emotion(content)
ui(progress.configure, value=80)
Enter fullscreen mode Exit fullscreen mode

Final output:

log_line(f"Detected Emotion: {emotion}")
log_line(f"Confidence: {confidence}%")
ui(progress.configure, value=100)
Enter fullscreen mode Exit fullscreen mode

โ“ Step 14: Help Window

A simple help dialog using Toplevel.

def show_help():
    win = tb.Toplevel(app)
    win.title("๐Ÿ“˜ TEXT2EMO โ€“ Help")
    win.geometry("300x360")
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”˜ Step 15: Buttons

We connect everything with buttons.

tb.Button(
    bottom_bar,
    text="Analyze Text",
    bootstyle="success",
    command=lambda: threading.Thread(
        target=analyze_text, daemon=True
    ).start()
).grid(row=1, column=0)


Stop button:

tb.Button(
    bottom_bar,
    text="Stop",
    bootstyle="danger",
    command=lambda: stop_event.set()
).grid(row=1, column=1)


Help button:

tb.Button(
    bottom_bar,
    text="Help",
    bootstyle="info",
    command=show_help
).grid(row=1, column=3)
Enter fullscreen mode Exit fullscreen mode

๐Ÿš€ Step 16: Run the App

Finally, start the application loop.

app.mainloop()
Enter fullscreen mode Exit fullscreen mode

๐ŸŽ‰ Final Thoughts

Youโ€™ve just built a fully functional emotion detection desktop app using pure Python!

Possible Enhancements

Add NLP libraries (TextBlob / spaCy)

Save analysis results to file

Dark/light theme toggle

Package as an executable

๐Ÿ”— Source Code:
https://github.com/rogers-cyber/TEXT2EMO

Top comments (0)