Building a GUI-Based URL Shortener in Python with Tkinter and MySQL
This tutorial walks through creating a Python GUI application using Tkinter to convert long URLs into short ones, installing required libraries, setting up MySQL tables to store mappings, and providing complete example code that handles validation, database interaction, and user interface events.
This guide explains how to build a Python GUI program with Tkinter that converts long URLs into short links and stores the mappings in a MySQL database to prevent duplicate short URLs.
First, ensure the required libraries are installed: pip install tk, pip install requests, and pip install pymysql.
Next, create the MySQL database and table to hold the URL pairs.
CREATE DATABASE IF NOT EXISTS url_shortener;</code>
<code>USE url_shortener;</code>
<code>CREATE TABLE IF NOT EXISTS url_mapping (</code>
<code> id INT AUTO_INCREMENT PRIMARY KEY,</code>
<code> original_url TEXT NOT NULL,</code>
<code> short_url VARCHAR(255) UNIQUE NOT NULL</code>
<code>);The following Python script demonstrates the complete implementation, including imports, database connection, short‑URL generation, URL validation, GUI layout, and event handling.
import tkinter as tk</code>
<code>from tkinter import messagebox</code>
<code>import requests</code>
<code>import pymysql</code>
<code>import string</code>
<code>import random</code>
<code>from urllib.parse import urlparse</code>
<code># Connect to the database</code>
<code>def connect_db():</code>
<code> conn = pymysql.connect(host='localhost', user='root', password='rootroot', db='url_shortener')</code>
<code> return conn</code>
<code># Generate a short URL</code>
<code>def generate_short_url(length=6):</code>
<code> letters_and_digits = string.ascii_letters + string.digits</code>
<code> return ''.join(random.choice(letters_and_digits) for _ in range(length))</code>
<code># Save URL mapping to the database</code>
<code>def save_url_to_db(original_url, short_url):</code>
<code> conn = connect_db()</code>
<code> cursor = conn.cursor()</code>
<code> try:</code>
<code> cursor.execute("INSERT INTO url_mapping (original_url, short_url) VALUES (%s, %s)", (original_url, short_url))</code>
<code> conn.commit()</code>
<code> return True</code>
<code> except pymysql.err.IntegrityError:</code>
<code> messagebox.showerror("错误", "该短链接已被占用!,请重新生成")</code>
<code> return False</code>
<code> finally:</code>
<code> cursor.close()</code>
<code> conn.close()</code>
<code># Validate URL format</code>
<code>def is_valid_url(url):</code>
<code> """检查给定的字符串是否为有效的URL。"""</code>
<code> try:</code>
<code> result = urlparse(url)</code>
<code> return all([result.scheme, result.netloc])</code>
<code> except ValueError:</code>
<code> return False</code>
<code># GUI callback</code>
<code>def on_convert_click():</code>
<code> original_url = entry_original.get()</code>
<code> if not is_valid_url(original_url):</code>
<code> messagebox.showerror("错误", "请输入一个有效的长链接!")
<code> return</code>
<code> short_url = generate_short_url()</code>
<code> if save_url_to_db(original_url, short_url):</code>
<code> messagebox.showinfo("成功", f"长链接已转换为短链接: {short_url}")</code>
<code> else:</code>
<code> pass # Handle failure if needed</code>
<code># Initialize the Tkinter window</code>
<code>app = tk.Tk()</code>
<code>app.title("长链接转短链接服务")</code>
<code>label_original = tk.Label(app, text="请输入长链接:")</code>
<code>label_original.pack()</code>
<code>entry_original = tk.Entry(app)</code>
<code>entry_original.pack()</code>
<code>button_convert = tk.Button(app, text="转换", command=on_convert_click)</code>
<code>button_convert.pack()</code>
<code>app.mainloop()Running this program provides a simple desktop tool that shortens URLs, stores them persistently, and alerts the user when a generated short link collides with an existing entry.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
