Have you ever wanted a quick and easy way to shorten long URLs? In this tutorial, I’ll show you how to create a Python-based URL shortener application with a modern graphical user interface (GUI) using PyQt5. By the end, you’ll have a sleek application that allows users to input long URLs, generate shorter ones, and copy them to the clipboard.
This project is beginner-friendly and demonstrates how to combine Python libraries for functionality and design. Let’s get started.
Why Build a URL Shortener?
A URL shortener is a fun and practical Python project to enhance your skills. Here’s what you’ll learn:
- Using PyQt5 to create a polished GUI application.
- Incorporating the pyshorteners library to generate short URLs.
- Styling PyQt5 GUIs with stylesheets, similar to web design.
- Structuring Python code with Object-Oriented Programming (OOP).
The best part? This project isn’t just educational — it’s also highly useful and a great way to boost your portfolio with something that has practical relevance.
Let’s dive in.
Project Prerequisites
Before we begin coding, let’s review the skills and tools needed for this tutorial.
Don’t worry if you’re not a Python expert just yet! Having a few basics under your belt will make this journey smoother and more enjoyable.
Basic Python Knowledge
You should be familiar with:
- Variables, functions, and loops.
- Basic object-oriented programming concepts.
Required Libraries
We’ll use the following Python libraries:
- PyQt5 for building the GUI.
- pyshorteners for generating short URLs.
Install the required libraries with:
pip install pyqt5 pyshorteners
A Curious and Experimental Mind
For me, experimenting and making small adjustments is one of the keys to learning coding. So, be ready to explore and debug as you go along!
Step 1: Set Up Your Project
Before we start coding, let’s set up the project:
1. Make sure Python is installed on your computer. If not, download it from the official Python website.
2. Open your favorite code editor or IDE.
3. Create a new Python file, for example, url_shortener.py.
Great, now, let's dive head first into our Python editor to get this build started.
Step 2: Import Required Libraries
Let’s begin by importing the libraries we’ll use in this project:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QLineEdit, QPushButton, QMessageBox
import pyshorteners
Step 3: Structuring the Application with OOP
We’ll use Object-Oriented Programming (OOP) to structure the application. Here’s an overview of the URLShortenerApp class:
- __init__ Method: Initializes the app window and calls the init_ui method.
- init_ui Method: Sets up the GUI components.
- shorten_url Method: Shortens the URL entered by the user.
- copy_to_clipboard Method: Copies the short URL to the clipboard.
Here’s the skeleton of the class:
class URLShortenerApp(QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
pass
def shorten_url(self):
pass
def copy_to_clipboard(self):
pass
Step 4: Building the User Interface
Let’s define the init_ui method to create the user interface. The GUI will include:
- A text input field for the long URL.
- A button to generate the short URL.
- A label to display the shortened URL.
- A button to copy the short URL to the clipboard.
def init_ui(self):
self.setWindowTitle("URL Shortener")
self.setGeometry(100, 100, 400, 250)
layout = QVBoxLayout()
# Instruction label
self.label = QLabel("Enter the URL you want to shorten:")
layout.addWidget(self.label)
# Input field
self.url_input = QLineEdit()
self.url_input.setPlaceholderText("Enter your URL here...")
layout.addWidget(self.url_input)
# Shorten button
self.shorten_button = QPushButton("Shorten URL")
self.shorten_button.clicked.connect(self.shorten_url)
layout.addWidget(self.shorten_button)
# Label to display the short URL
self.short_url_label = QLabel()
layout.addWidget(self.short_url_label)
# Copy button
self.copy_button = QPushButton("Copy to Clipboard")
self.copy_button.clicked.connect(self.copy_to_clipboard)
self.copy_button.setEnabled(False)
layout.addWidget(self.copy_button)
self.setLayout(layout)
Step 5: Styling with PyQt5 Stylesheets
PyQt5 stylesheets allow us to style the app with CSS-like syntax. Let’s add a clean, modern look with blue tones and rounded buttons:
# Apply styles
self.setStyleSheet("""
QWidget {
background-color: #f7f9fc;
}
QLabel {
color: #003366;
font-size: 14px;
font-weight: bold;
}
QLineEdit {
border: 2px solid #007BFF;
border-radius: 5px;
padding: 8px;
font-size: 14px;
}
QPushButton {
background-color: #007BFF;
color: white;
border-radius: 5px;
padding: 10px;
font-size: 14px;
font-weight: bold;
}
QPushButton:hover {
background-color: #0056b3;
}
""")
Step 6: Implementing Shorten URL Logic
The shorten_url method uses the pyshorteners library to generate short URLs. Here’s how it works:
1. Create a Shortener object.
2. Use the tinyurl.short() method to generate the short URL.
3. Display the short URL as a clickable hyperlink.
4. Enable the copy button.
def shorten_url(self):
long_url = self.url_input.text().strip()
if not long_url:
QMessageBox.warning(self, "Input Error", "Please enter a URL to shorten.")
return
try:
# Create a Shortener object
shortener = pyshorteners.Shortener()
# Generate the short URL
short_url = shortener.tinyurl.short(long_url)
# Display the short URL
self.short_url_label.setText(f"Short URL: <a href='{short_url}' style='color:#007BFF;'>{short_url}</a>")
self.short_url_label.setOpenExternalLinks(True)
# Enable the copy button
self.copy_button.setEnabled(True)
except Exception as e:
QMessageBox.critical(self, "Error", f"Failed to shorten URL: {str(e)}")
Step 7: Implementing Copy-to-Clipboard
The copy_to_clipboard method copies the short URL to the system clipboard and displays a confirmation message:
def copy_to_clipboard(self):
short_url = self.short_url_label.text().replace("Short URL: ", "").strip()
if short_url:
QApplication.clipboard().setText(short_url)
QMessageBox.information(self, "Copied", "Short URL copied to clipboard!")
Step 8: Running the Application
Finally, initialize and run the PyQt5 application:
if __name__ == "__main__":
app = QApplication(sys.argv)
window = URLShortenerApp()
window.show()
sys.exit(app.exec_())
Full Program Source Code
Here’s the complete code for the URL shortener application:
'''
Hackr.io Python Tutorial: URL Shortener
'''
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QLineEdit, QPushButton, QMessageBox
import pyshorteners
class URLShortenerApp(QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
self.setWindowTitle("URL Shortener")
self.setGeometry(100, 100, 400, 250)
layout = QVBoxLayout()
# Instruction label
self.label = QLabel("Enter the URL you want to shorten:")
layout.addWidget(self.label)
# Input field
self.url_input = QLineEdit()
self.url_input.setPlaceholderText("Enter your URL here...")
layout.addWidget(self.url_input)
# Shorten button
self.shorten_button = QPushButton("Shorten URL")
self.shorten_button.clicked.connect(self.shorten_url)
layout.addWidget(self.shorten_button)
# Label to display the short URL
self.short_url_label = QLabel()
layout.addWidget(self.short_url_label)
# Copy button
self.copy_button = QPushButton("Copy to Clipboard")
self.copy_button.clicked.connect(self.copy_to_clipboard)
self.copy_button.setEnabled(False)
layout.addWidget(self.copy_button)
self.setLayout(layout)
# Apply styles
self.setStyleSheet("""
QWidget {
background-color: #f7f9fc;
}
QLabel {
color: #003366;
font-size: 14px;
font-weight: bold;
}
QLineEdit {
border: 2px solid #007BFF;
border-radius: 5px;
padding: 8px;
font-size: 14px;
}
QPushButton {
background-color: #007BFF;
color: white;
border-radius: 5px;
padding: 10px;
font-size: 14px;
font-weight: bold;
}
QPushButton:hover {
background-color: #0056b3;
}
""")
def shorten_url(self):
long_url = self.url_input.text().strip()
if not long_url:
QMessageBox.warning(self, "Input Error", "Please enter a URL to shorten.")
return
try:
# Create a Shortener object
shortener = pyshorteners.Shortener()
# Generate the short URL
short_url = shortener.tinyurl.short(long_url)
# Display the short URL
self.short_url_label.setText(f"Short URL: <a href='{short_url}' style='color:#007BFF;'>{short_url}</a>")
self.short_url_label.setOpenExternalLinks(True)
# Enable the copy button
self.copy_button.setEnabled(True)
except Exception as e:
QMessageBox.critical(self, "Error", f"Failed to shorten URL: {str(e)}")
def copy_to_clipboard(self):
short_url = self.short_url_label.text().replace("Short URL: ", "").strip()
if short_url:
QApplication.clipboard().setText(short_url)
QMessageBox.information(self, "Copied", "Short URL copied to clipboard!")
if __name__ == "__main__":
app = QApplication(sys.argv)
window = URLShortenerApp()
window.show()
sys.exit(app.exec_())
Wrapping Up
You’ve just built a fully functional URL shortener application using Python and PyQt5. This project demonstrates how you can combine functionality with modern design to create a sleek, user-friendly application. By integrating pyshorteners, you’ve added the power to generate short URLs in just a few clicks.
Feel free to enhance this project by:
- Adding URL validation to ensure only valid URLs are processed.
- Supporting multiple shortening services from the pyshorteners library.
- Adding a history feature to save and display previously shortened URLs.
Happy coding!