SoFunction
Updated on 2025-04-11

Python+tkinter implements dynamic connection to database

When developing GUI programs using Tkinter (tk), there are several ways for users to freely change database connection addresses instead of writing them to death in code. Here are some implementation methods:

Method 1: Use the input box to let the user manually enter the database address

You can add an input box (Entry) to the GUI, allowing the user to manually enter the database address. Then when connecting to the database, get the address from the input box.

Sample code:

import tkinter as tk
from tkinter import messagebox
import   # Assume that using MySQL database
def connect_to_database():
    db_address = db_address_entry.get()  # Get the database address entered by the user    db_user = db_user_entry.get()        # Get the username entered by the user    db_password = db_password_entry.get()  # Get the password entered by the user    db_name = db_name_entry.get()        # Get the database name entered by the user
    try:
        # Connect to the database using the parameters entered by the user        connection = (
            host=db_address,
            user=db_user,
            password=db_password,
            database=db_name
        )
        if connection.is_connected():
            ("success", "The database connection is successful!")
            # You can continue to perform database operations here    except  as err:
        ("mistake", f"Connection failed:{err}")

# Create the main windowroot = ()
("Database Connection")

# Add input boxes and tags(root, text="Database Address:").grid(row=0, column=0)
db_address_entry = (root)
db_address_entry.grid(row=0, column=1)

(root, text="username:").grid(row=1, column=0)
db_user_entry = (root)
db_user_entry.grid(row=1, column=1)

(root, text="password:").grid(row=2, column=0)
db_password_entry = (root, show="*")  # Password hidden displaydb_password_entry.grid(row=2, column=1)

(root, text="Database Name:").grid(row=3, column=0)
db_name_entry = (root)
db_name_entry.grid(row=3, column=1)

# Add a connection buttonconnect_button = (root, text="Connect the database", command=connect_to_database)
connect_button.grid(row=4, column=0, columnspan=2)

# Run the main loop()

Method 2: Use configuration files to save the database address

You can save the database connection information in a configuration file (such as .txt or .json file), and then read the contents of the configuration file when the program starts. Users can manually modify the configuration file to change the database address.

Sample code (using .txt configuration file):

Create the configuration file db_config.txt:

host=localhost
user=root
password=your_password
database=my_database

Read the configuration file and connect to the database:

import tkinter as tk
from tkinter import messagebox
import 

def read_config():
    config = {}
    with open("db_config.txt", "r") as file:
        for line in file:
            key, value = ().split("=")
            config[key] = value
    return config

def connect_to_database():
    config = read_config()
    try:
        connection = (
            host=config["host"],
            user=config["user"],
            password=config["password"],
            database=config["database"]
        )
        if connection.is_connected():
            ("success", "The database connection is successful!")
            # You can continue to perform database operations here    except  as err:
        ("mistake", f"Connection failed:{err}")

# Create the main windowroot = ()
("Database Connection")

# Add a connection buttonconnect_button = (root, text="Connect the database", command=connect_to_database)
connect_button.pack()

# Run the main loop()

Method 3: Combining input box and configuration file

You can combine method one and method two, so that users can choose to enter the database address directly or load the address in the configuration file.

Sample code:

import tkinter as tk
from tkinter import messagebox, filedialog
import 

def connect_to_database():
    db_address = db_address_entry.get()
    db_user = db_user_entry.get()
    db_password = db_password_entry.get()
    db_name = db_name_entry.get()

    try:
        connection = (
            host=db_address,
            user=db_user,
            password=db_password,
            database=db_name
        )
        if connection.is_connected():
            ("success", "The database connection is successful!")
            # You can continue to perform database operations here    except  as err:
        ("mistake", f"Connection failed:{err}")

def load_config():
    file_path = (filetypes=[("Profile", "*.txt")])
    if file_path:
        config = {}
        with open(file_path, "r") as file:
            for line in file:
                key, value = ().split("=")
                config[key] = value
        db_address_entry.delete(0, )
        db_address_entry.insert(0, ("host", ""))
        db_user_entry.delete(0, )
        db_user_entry.insert(0, ("user", ""))
        db_password_entry.delete(0, )
        db_password_entry.insert(0, ("password", ""))
        db_name_entry.delete(0, )
        db_name_entry.insert(0, ("database", ""))

# Create the main windowroot = ()
("Database Connection")

# Add input boxes and tags(root, text="Database Address:").grid(row=0, column=0)
db_address_entry = (root)
db_address_entry.grid(row=0, column=1)

(root, text="username:").grid(row=1, column=0)
db_user_entry = (root)
db_user_entry.grid(row=1, column=1)

(root, text="password:").grid(row=2, column=0)
db_password_entry = (root, show="*")
db_password_entry.grid(row=2, column=1)

(root, text="Database Name:").grid(row=3, column=0)
db_name_entry = (root)
db_name_entry.grid(row=3, column=1)

# Add connection button and load configuration buttonconnect_button = (root, text="Connect the database", command=connect_to_database)
connect_button.grid(row=4, column=0, columnspan=2)

load_config_button = (root, text="Loading configuration file", command=load_config)
load_config_button.grid(row=5, column=0, columnspan=2)

# Run the main loop()

Summarize

Method 1: Suitable for simple scenarios, users can directly enter the database address in the GUI.

Method 2: Suitable for scenarios where database address needs to be changed frequently, users update connection information by modifying configuration files.

Method 3: Combining the advantages of the first two methods, it provides a more flexible user experience.

You can choose the right method according to your actual needs.

This is the article about Python+tkinter implementing dynamic connection to databases. For more related content on Python dynamic connection to databases, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!