URL Shortner – Python Source Code

  • Code
  • Code With GUI
Python
# Import the pyshorteners module
import pyshorteners

# Creating a function to shorten the given URL
def url_shortner(url):
    # Create a shortener variable
    shurl = pyshorteners.Shortener()

    # Shorten the URL using the tinyurl service
    return shurl.tinyurl.short(url)

# Print a welcome message
print ("\n ** Welcome To URL Shortner **")

# Take user input for the long URL to be shortened
long_url = input("Enter the long URL you want to shorten : ")

# Call the url_shortener function to get the shortened URL
short_url = url_shortner(long_url)

# Display the shortened URL
print (f"Shorterned URL : {short_url}")

# URL Shortner Source Code - By Codotix
Python
# Importing required modules
import pyshorteners
import tkinter as tk 
import tkinter.messagebox

# Create function to shorten the URL and display it
def url_shortner():
    url = url_entry.get()
    if not url:
        tkinter.messagebox.showerror("Error", "Please enter a URL")
        return
    
    # Create a shortener variable
    shurl = pyshorteners.Shortener()

    # Shorten the URL using the tinyurl service
    shortend_url = shurl.tinyurl.short(url)

    # Update the label to display the shortened URL
    shorten_url.config(text="Shorten URL: " + shortend_url)

    # Enable the "Copy to Clipboard" button
    copy_button.config(state=tk.NORMAL)

# Create function to copy the shortened URL to clipboard
def copy_to_clipboard():

    # Get the shortened URL from the label text
    shortened_url = shorten_url.cget("text").split(" ")[-1]

    # Clear the clipboard and append the shortened URL
    root.clipboard_clear()
    root.clipboard_append(shortened_url)
    root.update()

    # Show a copied message
    tkinter.messagebox.showinfo("Copied", "URL copied to clipboard!")

# Create the main Tkinter window
root = tk.Tk()
root.geometry("500x500")
root.title("URL Shortner")

# Label for the URL entry
enter_text = tk.Label(root, text="Enter URL You Want To Shorten :", font="arial 18 bold")
enter_text.pack(pady=(30, 0))

# Entry widget to input the URL
url_entry = tk.Entry(root, font="arial 16")
url_entry.pack(pady=(10, 15))

# Button to activate URL shortening
shorten_button = tk.Button(root, text="Click To Shorten", font="arial 16", command=url_shortner)
shorten_button.pack(pady=20)

# Label to display the shortened URL
shorten_url =  tk.Label(root, text="", font="arial 15")
shorten_url.pack(pady=20)

# Button to copy shortened URL to clipboard
copy_button = tk.Button(root, text="Copy to Clipboard", font="arial 16", state=tk.DISABLED, command=copy_to_clipboard)
copy_button.pack(pady=10)

# Start the Tkinter event loop
root.mainloop()

# URL Shortner Source Code - By Codotix

Leave a Comment

Your email address will not be published. Required fields are marked *