Language Detection in Python using Tkinter

Language detection is a crucial feature in today's globalized applications. This tutorial demonstrates how to build a language detection GUI application using Python's Tkinter library combined with the langdetect package. We'll create a user-friendly interface that identifies the language of user-inputted text.

What is Tkinter?

Tkinter is Python's standard GUI toolkit interface for the Tk windowing system. It's the most commonly used method for creating graphical user interfaces in Python and supports most Unix, Windows, and Macintosh platforms with a powerful, platform-independent windowing toolkit.

The Importance of Language Detection

Language detection determines the language in which a piece of text is written. This capability is essential for applications like sentiment analysis, content classification, and translation services. Integrating effective language detection can significantly enhance user experience and data processing capabilities.

Installing Required Libraries

We need two Python libraries for our language detection application ?

pip install langdetect

Note: Tkinter comes pre-installed with Python, so no separate installation is needed.

Basic Language Detection

The langdetect library provides a simple detect() function that accepts text input and returns the detected language's ISO 639-1 language code ?

from langdetect import detect

text = "Bonjour le monde"
language = detect(text)
print(f"Detected language: {language}")
Detected language: fr

Creating the GUI Application

Setting Up the Main Window

import tkinter as tk
from langdetect import detect

# Create main window
root = tk.Tk()
root.title("Language Detector")
root.geometry("400x300")
root.resizable(False, False)

# Add a title label
title_label = tk.Label(root, text="Language Detection Tool", 
                      font=("Arial", 16, "bold"))
title_label.pack(pady=20)

root.mainloop()

Adding Input Components

import tkinter as tk
from langdetect import detect

root = tk.Tk()
root.title("Language Detector")
root.geometry("400x300")

# Title
title_label = tk.Label(root, text="Language Detection Tool", 
                      font=("Arial", 16, "bold"))
title_label.pack(pady=20)

# Input instruction
instruction_label = tk.Label(root, text="Enter text to detect language:")
instruction_label.pack()

# Text entry field
text_entry = tk.Entry(root, width=40, font=("Arial", 12))
text_entry.pack(pady=10)

# Result label
result_label = tk.Label(root, text="", font=("Arial", 12), 
                       fg="blue", wraplength=350)
result_label.pack(pady=20)

root.mainloop()

Implementing Detection Function

import tkinter as tk
from langdetect import detect, LangDetectException

# Language code to name mapping
LANGUAGES = {
    'en': 'English', 'es': 'Spanish', 'fr': 'French', 'de': 'German',
    'it': 'Italian', 'pt': 'Portuguese', 'ru': 'Russian', 'ja': 'Japanese',
    'ko': 'Korean', 'zh-cn': 'Chinese (Simplified)', 'ar': 'Arabic',
    'hi': 'Hindi', 'tr': 'Turkish', 'nl': 'Dutch', 'sv': 'Swedish'
}

def detect_language():
    text = text_entry.get().strip()
    
    if not text:
        result_label.config(text="Please enter some text", fg="red")
        return
    
    try:
        language_code = detect(text)
        language_name = LANGUAGES.get(language_code, f"Unknown ({language_code})")
        result_label.config(text=f"Detected Language: {language_name}", fg="green")
    except LangDetectException:
        result_label.config(text="Unable to detect language. Please enter more text.", fg="red")

root = tk.Tk()
root.title("Language Detector")
root.geometry("400x300")

title_label = tk.Label(root, text="Language Detection Tool", 
                      font=("Arial", 16, "bold"))
title_label.pack(pady=20)

instruction_label = tk.Label(root, text="Enter text to detect language:")
instruction_label.pack()

text_entry = tk.Entry(root, width=40, font=("Arial", 12))
text_entry.pack(pady=10)

detect_button = tk.Button(root, text="Detect Language", 
                         command=detect_language, font=("Arial", 12))
detect_button.pack(pady=10)

result_label = tk.Label(root, text="", font=("Arial", 12), 
                       fg="blue", wraplength=350)
result_label.pack(pady=20)

# Clear button
clear_button = tk.Button(root, text="Clear", 
                        command=lambda: (text_entry.delete(0, tk.END), 
                                       result_label.config(text="")))
clear_button.pack()

root.mainloop()

Complete Application

Here's the complete language detection application with enhanced features ?

import tkinter as tk
from tkinter import scrolledtext
from langdetect import detect, detect_langs, LangDetectException

# Language code mapping
LANGUAGES = {
    'en': 'English', 'es': 'Spanish', 'fr': 'French', 'de': 'German',
    'it': 'Italian', 'pt': 'Portuguese', 'ru': 'Russian', 'ja': 'Japanese',
    'ko': 'Korean', 'zh-cn': 'Chinese (Simplified)', 'ar': 'Arabic',
    'hi': 'Hindi', 'tr': 'Turkish', 'nl': 'Dutch', 'sv': 'Swedish'
}

class LanguageDetectorApp:
    def __init__(self, root):
        self.root = root
        self.setup_ui()
    
    def setup_ui(self):
        self.root.title("Language Detector")
        self.root.geometry("500x400")
        
        # Title
        title = tk.Label(self.root, text="Language Detection Tool", 
                        font=("Arial", 18, "bold"))
        title.pack(pady=20)
        
        # Text input area
        tk.Label(self.root, text="Enter text:").pack()
        self.text_area = scrolledtext.ScrolledText(self.root, width=50, height=8)
        self.text_area.pack(pady=10)
        
        # Buttons frame
        buttons_frame = tk.Frame(self.root)
        buttons_frame.pack(pady=10)
        
        tk.Button(buttons_frame, text="Detect Language", 
                 command=self.detect_language).pack(side=tk.LEFT, padx=5)
        tk.Button(buttons_frame, text="Show Probabilities", 
                 command=self.show_probabilities).pack(side=tk.LEFT, padx=5)
        tk.Button(buttons_frame, text="Clear", 
                 command=self.clear_text).pack(side=tk.LEFT, padx=5)
        
        # Result area
        self.result_label = tk.Label(self.root, text="", font=("Arial", 12), 
                                   wraplength=450, justify=tk.LEFT)
        self.result_label.pack(pady=20)
    
    def detect_language(self):
        text = self.text_area.get(1.0, tk.END).strip()
        
        if not text:
            self.result_label.config(text="Please enter some text", fg="red")
            return
        
        try:
            language_code = detect(text)
            language_name = LANGUAGES.get(language_code, f"Unknown ({language_code})")
            self.result_label.config(
                text=f"Detected Language: {language_name} ({language_code})", 
                fg="green"
            )
        except LangDetectException:
            self.result_label.config(
                text="Unable to detect language. Please enter more text.", 
                fg="red"
            )
    
    def show_probabilities(self):
        text = self.text_area.get(1.0, tk.END).strip()
        
        if not text:
            self.result_label.config(text="Please enter some text", fg="red")
            return
        
        try:
            probabilities = detect_langs(text)
            result_text = "Language Probabilities:\n"
            for lang in probabilities[:3]:  # Show top 3
                lang_name = LANGUAGES.get(str(lang).split(':')[0], 
                                        str(lang).split(':')[0])
                result_text += f"{lang_name}: {lang.prob:.2%}\n"
            
            self.result_label.config(text=result_text, fg="blue")
        except LangDetectException:
            self.result_label.config(
                text="Unable to detect language. Please enter more text.", 
                fg="red"
            )
    
    def clear_text(self):
        self.text_area.delete(1.0, tk.END)
        self.result_label.config(text="")

# Run the application
if __name__ == "__main__":
    root = tk.Tk()
    app = LanguageDetectorApp(root)
    root.mainloop()

Testing the Application

Try entering different text samples to test the detector ?

  • English: "Hello, how are you today?"
  • Spanish: "Hola, ¿cómo estás hoy?"
  • French: "Bonjour, comment allez-vous?"
  • German: "Guten Tag, wie geht es Ihnen?"

Key Features

Feature Function Benefit
Single Detection detect() Quick language identification
Probability Detection detect_langs() Shows confidence levels
Error Handling Exception catching Graceful failure handling

Conclusion

This tutorial demonstrated how to create a language detection GUI application using Tkinter and langdetect. The application provides both simple detection and probability-based analysis, making it suitable for various text processing needs. You can enhance this further by adding support for file input or integrating with translation APIs.

Updated on: 2026-03-27T08:03:05+05:30

585 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements