Instant YouTube Downloader in Python

Instant YouTube Downloader in Python

Build your own "Instant YouTube downloader" in Python within 5 minutes with cool GUI using Tkinter

Ever surfed web to find a good YouTube downloader and always ended up with frustrations due fake websites or excess ads. No worries if you follow this article to the very end you will have your own YouTube downloader built in python and you can also have the .exe file on your desktop such that you can download any YouTube videos just like that !!

Table of Contents

  • Overview

  • Prerequsites

  • Designing GUI

  • Coding

  • Complete source code

  • Converting to .exe file

Overview

Pytube is more like heart of this article/project. So first what is pytube ? Pytube is a lightweight, Pythonic, dependency-free, library for downloading YouTube Videos. It also makes it easy to filter based on type of stream you are interested i.e, you can download video with your preferred resolution.

Another important term in this article is Tkinter. So now What is tkinter ? Tkinter library is a standard GUI library for python. When python combined with tkinter provides a easiest way to build GUI applications

Prerequsites

To begin with our project first we need to install Pytube. To install pytube, you must have python 3.6 or greater if you don't have Python 3.6 or grater version download one here

Now we can head to install pytube you can simply achieve this by pip command, Open your terminal and write,

pip install pytube

After installing pytube we can proceed with our project initially we must import all required packages, Lets do it quickly

First lets import youtube from pytube

from pytube import YouTube

import everything from tkinter library

from tkinter import *

ttk module provides access to the Tk themed widget set so we should import that aswell

from tkinter import ttk

Last but not least import filedialog, Using this you can open a single file, a directory, save as file and much more. Here we will make use of it to askdirectory in which we want to save our video

from tkinter import filedialog

Designing GUI

We have done importing all required modules now lets start designing UI

Create an instance of tkinter frame

root=tk()

Give title to the frame

root.title("Instant YouTube Downloader")

set frame size

root.geometry("550x550")
root.columnconfigure(0,weight=1)

set background color to the frame

root.configure(bg="#1af0c1")

Lets add labels, entry box, buttons, combo box one by one in the required order

Simple syntax for these are label(master, options) master is nothing but the root in which we have created the instance for tkinter and options are several which includes bg()->background color, fg()->foreground color, font()->font style and sizes and so on.

pady() is to add padding to each widgets

.grid() adds each widget to the frame

heading=Label(root,text="✨Instant Youtube Downloader✨",font=("Comic Sans MS",20,"bold"),bg="#1af0c1")
heading.grid(pady=(75,0))

mainlabel=Label(root,text="Enter the URL below",font=("Comic Sans MS",20,"bold"),bg="#1af0c1")
mainlabel.grid(pady=(40,0))

urlEntered=StringVar()
entrybox=Entry(root,width=50,textvariable=urlEntered,)
entrybox.grid()

location=Button(root,text="choose Location",width="15",bg="#00634e",fg="white")
location.grid(pady=(30,10))

locationError = Label(root,text="Chosen path will be displayed here !! ",fg="red",font=("Comic Sans MS",10,"bold"),bg="#1af0c1")
locationError.grid()

Quality = Label(root,text="Select Preffered Quality",font=("Comic Sans MS",15,"bold"),bg="#1af0c1")
Quality.grid(pady=(20,0))

options = ["720p","144p","mp3"]
selectQuality = ttk.Combobox(root,values=options)
selectQuality.grid()

download=Button(root,text="Donwload",width=10,bg="#00634e",fg="white")
download.grid(pady=(30,0))

errorMsgFinal=Label(root,text=" ",fg="#005909",font=("Comic Sans MS",20,"bold"),bg="#1af0c1")
errorMsgFinal.grid(pady=(10,0))

Dont forget to add mainloop(), this method runs our application

root.mainloop()

Now our UI design is completed lets move to coding logic

Coding

To make this application work we need to write 2 functions one is to choose location in which we want to save our video and another one is to download video according to our preferred resolution.

First lets code chooseLocation function

Declare a variable fileLocation outside the function globally in which we will save the path.

fileLocation=""

Here we will use filedialog.askdirectory() to get the directory from the user,

def chooseLocation():
    global fileLocation
    fileLocation=filedialog.askdirectory()
    if(len(fileLocation)>1):
        locationError.config(text=fileLocation,fg="#005909")
    else:
        locationError.config(text="Please choose a folder",fg="red")

Also don't forgot to call this function in location button you can do this simply by adding command=chooseLocations as option in location button

command=chooseLocation

Now lets complete DownloadVideo function,

def DownloadVideo():

Fetch the quality selected from selectQuality combobox

    optionSelected=selectQuality.get()

Fetch the url from entry box using get() function

    url=entrybox.get()

If we get some url i.e, len(url)>1 create object of YouTube()

    if(len(url)>1):
        yt=YouTube(url)

from all available streams filter and fetch the required resolution according to the option selected from combo box which is ow stored in optionSelected variable

        if(optionSelected==options[0]):
            select=yt.streams.filter(progressive=True).first()
        elif(optionSelected==options[1]):
            select=yt.streams.filter(progressive=True,file_extension='mp4').last()
        elif(optionSelected==options[2]):
            select=yt.streams.filter(only_audio=True).first()
        else:
            errorMsgFinal.config(text="oopsiee")

Download the video in preferred location using download()

    select.download(fileLocation)
    errorMsgFinal.config(text="Download Completed!!")

Finally call this function in Download button you can do this simply by adding command=DownloadVideo as a option in Download button

command=DownloadVideo

Whoohoo !! We have built our own youtube downloader !!

Entire Source Code

from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from pytube import YouTube

fileLocation=""

def openLocation():
    global fileLocation
    fileLocation=filedialog.askdirectory()
    if(len(fileLocation)>1):
        locationError.config(text=fileLocation,fg="#005909")
    else:
        locationError.config(text="Please choose a folder",fg="red")

def DownloadVideo():
    optionSelected=selectQuality.get()
    url=entrybox.get()

    if(len(url)>1):
        yt=YouTube(url)

        if(optionSelected==options[0]):
            select=yt.streams.filter(progressive=True).first()
        elif(optionSelected==options[1]):
            select=yt.streams.filter(progressive=True,file_extension='mp4').last()
        elif(optionSelected==options[2]):
            select=yt.streams.filter(only_audio=True).first()
        else:
            errorMsgFinal.config(text="oopsiee")

    select.download(fileLocation)
    errorMsgFinal.config(text="Download Completed!!")



root=Tk()
root.title("Instant YouTube Downloader")
root.geometry("550x550")
root.columnconfigure(0,weight=1)
root.configure(bg="#1af0c1")

heading=Label(root,text="✨Instant Youtube Downloader✨",font=("Comic Sans MS",20,"bold"),bg="#1af0c1")
heading.grid(pady=(75,0))

mainlabel=Label(root,text="Enter the URL below",font=("Comic Sans MS",20,"bold"),bg="#1af0c1")
mainlabel.grid(pady=(40,0))

urlEntered=StringVar()
entrybox=Entry(root,width=50,textvariable=urlEntered,)
entrybox.grid()

location=Button(root,text="choose Location",width="15",bg="#00634e",fg="white",command=chooseLocation)
location.grid(pady=(30,10))

locationError = Label(root,text="Chosen path will be displayed here !! ",fg="red",font=("Comic Sans MS",10,"bold"),bg="#1af0c1")
locationError.grid()

Quality = Label(root,text="Select Preffered Quality",font=("Comic Sans MS",15,"bold"),bg="#1af0c1")
Quality.grid(pady=(20,0))

options = ["720p","144p","mp3"]
selectQuality = ttk.Combobox(root,values=options)
selectQuality.grid()

download = Button(root,text="Donwload",width=10,bg="#00634e",fg="white",command=DownloadVideo)
download.grid(pady=(30,0))

errorMsgFinal=Label(root,text=" ",fg="#005909",font=("Comic Sans MS",20,"bold"),bg="#1af0c1")
errorMsgFinal.grid(pady=(10,0))

root.mainloop()

Converting to .exe file

To covert your python file to exe file we need to install pyinstaller module

pip install pyintsaller

Then open your cmd move to the directory in which you want to build your exe file and type the following command

pyinstaller --onefile -w YoutubeDownloader.py

pyinstaller --onefile -w-->keyword YoutubeDownloader.py-->Your python filename

Once you enter this command it will build several files once it finish its compilation you willl have several folders in the same directory navigate to "dist" folder inside which your exe file will be located create a shortcut for the exe file to your desktop so that you can download any youtube video simply by a click.

Hope you enjoyed !!