Validate User Input in Tkinter – Error Handling and Form Validation in Python GUI

 

← Back to Home

๐Ÿ Python UI Programming Series — Part 6: Form Validation and Error Handling in Tkinter


๐Ÿ“˜ Overview

Now that your GUI app can save and retrieve data, it’s time to make it robust and user-proof. That means:

  • Validating user input (like empty fields or incorrect email formats)

  • Preventing crashes using error handling

  • Showing clear and helpful feedback to users

This part covers:

  • Types of input validation

  • Using try/except for safe operations

  • User-friendly error messages with messagebox


❗ Why Validation & Error Handling Matter

  • Prevents bad data from being stored

  • Avoids runtime crashes

  • Helps users correct their mistakes easily


✅ Validating Input Fields

Let’s enhance the example from Part 5 by validating name and email:

๐Ÿงช 1. Check Empty Fields

if not name or not email:
    messagebox.showwarning("Input Error", "All fields are required!")
    return

๐Ÿงช 2. Basic Email Format Validation

import re

email_pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
if not re.match(email_pattern, email):
    messagebox.showwarning("Invalid Email", "Please enter a valid email address.")
    return

You can add this check before inserting the record.


๐Ÿ”’ Error Handling with try / except

Use try/except when connecting to the database or performing any risky operation:

try:
    conn = sqlite3.connect("users.db")
    conn.execute("INSERT INTO users (name, email) VALUES (?, ?)", (name, email))
    conn.commit()
except Exception as e:
    messagebox.showerror("Database Error", f"Something went wrong:\n{e}")
finally:
    conn.close()

This ensures:

  • Errors are caught and reported

  • The connection is always closed


✅ Final: Robust Tkinter Form with Validation

import tkinter as tk
from tkinter import messagebox
import sqlite3
import re

def save_to_db():
    name = entry_name.get().strip()
    email = entry_email.get().strip()

    if not name or not email:
        messagebox.showwarning("Input Error", "All fields are required.")
        return

    email_pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
    if not re.match(email_pattern, email):
        messagebox.showwarning("Invalid Email", "Please enter a valid email.")
        return

    try:
        conn = sqlite3.connect("users.db")
        conn.execute("INSERT INTO users (name, email) VALUES (?, ?)", (name, email))
        conn.commit()
        messagebox.showinfo("Success", "User saved successfully!")
        entry_name.delete(0, tk.END)
        entry_email.delete(0, tk.END)
    except Exception as e:
        messagebox.showerror("Database Error", f"Error: {e}")
    finally:
        conn.close()

root = tk.Tk()
root.title("Validated Form")
root.geometry("300x200")

tk.Label(root, text="Name:").pack(pady=5)
entry_name = tk.Entry(root)
entry_name.pack()

tk.Label(root, text="Email:").pack(pady=5)
entry_email = tk.Entry(root)
entry_email.pack()

tk.Button(root, text="Save", command=save_to_db).pack(pady=10)

root.mainloop()

๐Ÿ’ก Recap

In this part, you’ve learned:

  • How to validate input fields (e.g., empty values, email format)

  • How to use try/except to prevent crashes

  • How to show clear feedback using messagebox


๐Ÿš€ Coming Up in Part 7:

“Advanced Widgets in Tkinter: Combobox, Checkbutton, Radiobutton, and More”

  • Collect user choices through interactive elements

  • Use dropdowns, toggles, and selections in forms



No comments:

Post a Comment

Featured Post

Add Keyboard Shortcuts to Tkinter GUI – Python Hotkeys with Bind Examples

  ← Back to Home ⌨️ Bonus Part 5: Keyboard Shortcuts & Hotkeys in Tkinter – Boost App Productivity ๐Ÿ“˜ Overview Keyboard shortcuts ...

Popular Posts