py4u blog

Create MySQL Database Login Page in Python using Tkinter

In this blog post, we'll explore how to create a MySQL database login page using Python's Tkinter library. Tkinter is a standard GUI (Graphical User Interface) toolkit for Python, and MySQL is a popular relational database management system. This combination allows us to build a simple yet functional login interface that can interact with a MySQL database.

2026-07

Table of Contents#

  1. Prerequisites
  2. Setting up the MySQL Database
  3. Installing Required Python Libraries
  4. Building the Tkinter GUI
  5. Connecting to the MySQL Database
  6. Implementing the Login Functionality
  7. Best Practices
  8. Example Usage
  9. References

1. Prerequisites#

  • Python: Make sure you have Python installed on your system. You can download it from the official Python website (https://www.python.org/).
  • MySQL Server: Install a MySQL server. You can use MySQL Community Server (https://dev.mysql.com/downloads/mysql/).
  • Basic knowledge of Python programming and SQL: Familiarity with Python syntax and basic SQL commands (like SELECT, INSERT, etc.) will be helpful.

2. Setting up the MySQL Database#

Step 1: Create a Database#

Open your MySQL client (e.g., MySQL Shell or MySQL Workbench). Run the following SQL command to create a new database (let's call it login_db):

CREATE DATABASE login_db;

Step 2: Create a Table#

Inside the login_db, create a table to store user credentials. For simplicity, let's create a table named users with columns username (VARCHAR) and password (VARCHAR):

USE login_db;
CREATE TABLE users (
    username VARCHAR(50) NOT NULL,
    password VARCHAR(50) NOT NULL
);

Step 3: Insert Sample Data (Optional)#

You can insert some sample user data for testing purposes. For example:

INSERT INTO users (username, password) VALUES ('user1', 'pass1'), ('user2', 'pass2');

3. Installing Required Python Libraries#

  • tkinter: It comes pre-installed with Python. So, no need to install it separately.
  • mysql-connector-python: This library is used to connect Python to MySQL. Install it using pip:
pip install mysql-connector-python

4. Building the Tkinter GUI#

Step 1: Import Libraries#

import tkinter as tk
from tkinter import messagebox
import mysql.connector

Step 2: Create the Main Window#

root = tk.Tk()
root.title("MySQL Login Page")
root.geometry("400x300")

Step 3: Add Widgets (Labels and Entries)#

# Username Label and Entry
username_label = tk.Label(root, text="Username:")
username_label.pack()
username_entry = tk.Entry(root)
username_entry.pack()
 
# Password Label and Entry
password_label = tk.Label(root, text="Password:")
password_label.pack()
password_entry = tk.Entry(root, show="*")  # Show * for password masking
password_entry.pack()

Step 4: Add a Login Button#

def login():
    # Functionality will be added later
    pass
 
login_button = tk.Button(root, text="Login", command=login)
login_button.pack()

5. Connecting to the MySQL Database#

Step 1: Define the Connection Function (Inside the login Function or as a Separate Function)#

def connect_to_db():
    try:
        mydb = mysql.connector.connect(
            host="localhost",  # Change if your MySQL server is on a different host
            user="your_username",  # Replace with your MySQL username
            password="your_password",  # Replace with your MySQL password
            database="login_db"
        )
        return mydb
    except mysql.connector.Error as err:
        messagebox.showerror("Error", f"Something went wrong: {err}")
        return None

6. Implementing the Login Functionality#

Step 1: Update the login Function#

def login():
    username = username_entry.get()
    password = password_entry.get()
 
    mydb = connect_to_db()
    if mydb:
        mycursor = mydb.cursor()
        query = "SELECT * FROM users WHERE username = %s AND password = %s"
        mycursor.execute(query, (username, password))
        result = mycursor.fetchone()
 
        if result:
            messagebox.showinfo("Success", "Login successful!")
        else:
            messagebox.showerror("Error", "Invalid username or password")
 
        mydb.close()

7. Best Practices#

  • Input Validation: Before connecting to the database, validate the input (e.g., check if the username and password fields are not empty).
  • Error Handling: As shown in the connect_to_db function, handle database connection errors gracefully.
  • Password Security: In a real-world scenario, consider using hashing algorithms (like bcrypt in Python) to store passwords securely in the database instead of plain text.
  • Use Parameterized Queries: As we did with mycursor.execute(query, (username, password)), this helps prevent SQL injection attacks.

8. Example Usage#

  • Run the Python script. The Tkinter window will appear.
  • Enter a valid username and password (from the sample data you inserted earlier if you did).
  • Click the "Login" button. If the credentials match, you'll get a success message; otherwise, an error message.

9. References#

This is a basic example of creating a MySQL database login page using Tkinter. You can further enhance it by adding features like user registration, password reset, etc.