Prerequisites:
- Tkinter
- pyyoutube
- pytube
- Threading in Tkinter
- YouTube API
Python provides various options for developing Graphical User Interfaces (GUIs). Among these, Tkinter is the most commonly used method, as it is a standard Python interface to the Tk GUI toolkit included with Python. Using Tkinter with Python is the quickest and easiest way to create GUI applications.
In this article, we will explore how to create a GUI application to download a YouTube video or an entire YouTube playlist using Python.
First, we will discuss the pyyoutube module, which offers an easy way to work with the YouTube Data API V3.
How To Install
pip install python-youtube
pip install pytube
In this section, we’ll learn how to download specific videos from a YouTube playlist using Tkinter in Python.
Steps:
- We’ll get all the video links from the YouTube playlist using the pyyoutube module.
- Then, we’ll pick the video links we want to download.
- Finally, we’ll download each selected video one by one using the pytube module.
Let us go for the code with a step by step implementation
Create a Tkinter window and add Buttons, Labels, Scrollbar, etc…
# Import Required Modules
from tkinter import *
# Create Object
root = Tk()
# Set geometry
root.geometry('400x400')
# Add Label
Label(root, text="Youtube Playlist Downloader",
font="italic 15 bold").pack(pady=10)
Label(root, text="Enter Playlist URL:-", font="italic 10").pack()
# Add Entry box
playlistId = Entry(root, width=60)
playlistId.pack(pady=5)
# Add Button
get_videos = Button(root, text="Get Videos")
get_videos.pack(pady=10)
# Add Scorllbar
scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=BOTH)
list_box = Listbox(root, selectmode="multiple")
list_box.pack(expand=YES, fill="both")
list_box.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=list_box.yview)
download_start = Button(root, text="Download Start", state=DISABLED)
download_start.pack(pady=10)
# Execute Tkinter
root.mainloop()

Now we will create three functions:
get_list_videos: This function will generate a list of all video links from a YouTube playlist.threading: This function handles threading in Tkinter.download_videos: This function is responsible for downloading YouTube videos.
def get_list_videos():
global playlist_item_by_id
# Clear ListBox
list_box.delete(0, 'end')
# Create API Object
api = Api(api_key='Enter API Key')
if "youtube" in playlistId.get():
playlist_id = playlistId.get()[len(
"https://www.youtube.com/playlist?list="):]
else:
playlist_id = playlistId.get()
# Get list of video links
playlist_item_by_id = api.get_playlist_items(
playlist_id=playlist_id, count=None, return_json=True)
# Iterate through all video links and insert into listbox
for index, videoid in enumerate(playlist_item_by_id['items']):
list_box.insert(
END, f" {str(index+1)}. {videoid['contentDetails']['videoId']}")
download_start.config(state=NORMAL)
def threading():
# Call download_videos function
t1 = Thread(target=download_videos)
t1.start()
def download_videos():
download_start.config(state="disabled")
get_videos.config(state="disabled")
# Iterate through all selected videos
for i in list_box.curselection():
videoid = playlist_item_by_id['items'][i]['contentDetails']['videoId']
link = f"https://www.youtube.com/watch?v={videoid}"
yt_obj = YouTube(link)
filters = yt_obj.streams.filter(progressive=True, file_extension='mp4')
# download the highest quality video
filters.get_highest_resolution().download()
messagebox.showinfo("Success", "Video Successfully downloaded")
download_start.config(state="normal")
get_videos.config(state="normal")
Full Code:
# Import Required Modules
from tkinter import *
from pyyoutube import Api
from pytube import YouTube
from threading import Thread
from tkinter import messagebox
def get_list_videos():
global playlist_item_by_id
# Clear ListBox
list_box.delete(0, 'end')
# Create API Object
api = Api(api_key='Enter API Key')
if "youtube" in playlistId.get():
playlist_id = playlistId.get()[len(
"https://www.youtube.com/playlist?list="):]
else:
playlist_id = playlistId.get()
# Get list of video links
playlist_item_by_id = api.get_playlist_items(
playlist_id=playlist_id, count=None, return_json=True)
# Iterate through all video links and insert into listbox
for index, videoid in enumerate(playlist_item_by_id['items']):
list_box.insert(
END, f" {str(index+1)}. {videoid['contentDetails']['videoId']}")
download_start.config(state=NORMAL)
def threading():
# Call download_videos function
t1 = Thread(target=download_videos)
t1.start()
def download_videos():
download_start.config(state="disabled")
get_videos.config(state="disabled")
# Iterate through all selected videos
for i in list_box.curselection():
videoid = playlist_item_by_id['items'][i]['contentDetails']['videoId']
link = f"https://www.youtube.com/watch?v={videoid}"
yt_obj = YouTube(link)
filters = yt_obj.streams.filter(progressive=True, file_extension='mp4')
# download the highest quality video
filters.get_highest_resolution().download()
messagebox.showinfo("Success", "Video Successfully downloaded")
download_start.config(state="normal")
get_videos.config(state="normal")
# Create Object
root = Tk()
# Set geometry
root.geometry('400x400')
# Add Label
Label(root, text="Youtube Playlist Downloader",
font="italic 15 bold").pack(pady=10)
Label(root, text="Enter Playlist URL:-", font="italic 10").pack()
# Add Entry box
playlistId = Entry(root, width=60)
playlistId.pack(pady=5)
# Add Button
get_videos = Button(root, text="Get Videos", command=get_list_videos)
get_videos.pack(pady=10)
# Add Scrollbar
scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=BOTH)
list_box = Listbox(root, selectmode="multiple")
list_box.pack(expand=YES, fill="both")
list_box.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=list_box.yview)
download_start = Button(root, text="Download Start",
command=threading, state=DISABLED)
download_start.pack(pady=10)
# Execute Tkinter
root.mainloop()

Explanation of the above code:
# Import Required Modules
- This is a comment explaining that the following lines import necessary modules for the script.
from tkinter import *
- Imports all classes, functions, and variables from the Tkinter module, which is used for creating graphical user interfaces (GUIs) in Python.
from pyyoutube import Api
- Imports the
Apiclass from thepyyoutubemodule, which allows interaction with the YouTube Data API.
from pytube import YouTube
- Imports the
YouTubeclass from thepytubemodule, which is used for downloading videos from YouTube.
from threading import Thread
- Imports the
Threadclass from thethreadingmodule, which allows for concurrent execution of functions in separate threads.
from tkinter import messagebox
- Imports the
messageboxmodule from Tkinter, which is used to display message boxes in the GUI.
def get_list_videos():
- Defines a function named
get_list_videosthat will retrieve and display video links from a YouTube playlist.
global playlist_item_by_id
- Declares
playlist_item_by_idas a global variable, making it accessible outside the function.
list_box.delete(0, 'end')
- Clears all items in the list box widget, preparing it for a new set of video links.
api = Api(api_key='Enter API Key')
- Creates an
Apiobject using the provided YouTube API key to interact with the YouTube Data API.
if "youtube" in playlistId.get():
- Checks if the entered URL contains “youtube”, indicating it is a YouTube playlist URL.
playlist_id = playlistId.get()[len("https://www.youtube.com/playlist?list="):]
- Extracts the playlist ID from the YouTube URL by removing the fixed part of the URL.
else:
- Handles the case where the entered text is directly the playlist ID.
playlist_id = playlistId.get()
- Sets the playlist ID to the entered text if it doesn’t contain “youtube”.
playlist_item_by_id = api.get_playlist_items(playlist_id=playlist_id, count=None, return_json=True)
- Uses the
pyyoutubeAPI object to fetch all video items in the playlist and store them inplaylist_item_by_id.
for index, videoid in enumerate(playlist_item_by_id['items']):
- Iterates through the list of video items, with
indexas the loop counter andvideoidas the current video item.
list_box.insert(END, f" {str(index+1)}. {videoid['contentDetails']['videoId']}")
- Inserts each video ID into the list box, prefixed with its position number.
download_start.config(state=NORMAL)
- Enables the “Download Start” button once the list of videos is populated.
def threading():
- Defines a function named
threadingto handle threading for the video download process.
t1 = Thread(target=download_videos)
- Creates a new thread
t1that will run thedownload_videosfunction.
t1.start()
- Starts the thread
t1.
def download_videos():
- Defines a function named
download_videosthat will handle downloading videos from the YouTube playlist.
download_start.config(state="disabled")
- Disables the “Download Start” button to prevent multiple downloads at the same time.
get_videos.config(state="disabled")
- Disables the “Get Videos” button to prevent fetching new videos while downloads are in progress.
for i in list_box.curselection():
- Iterates through the currently selected items in the list box.
videoid = playlist_item_by_id['items'][i]['contentDetails']['videoId']
- Retrieves the video ID of the selected item using its index.
link = f"https://www.youtube.com/watch?v={videoid}"
- Constructs the full YouTube video URL using the video ID.
yt_obj = YouTube(link)
- Creates a
YouTubeobject for the video URL.
filters = yt_obj.streams.filter(progressive=True, file_extension='mp4')
- Filters the available streams to get only progressive streams with an MP4 file extension.
filters.get_highest_resolution().download()
- Downloads the highest quality version of the video.
messagebox.showinfo("Success", "Video Successfully downloaded")
- Displays a message box indicating that the video was successfully downloaded.
download_start.config(state="normal")
- Re-enables the “Download Start” button.
get_videos.config(state="normal")
- Re-enables the “Get Videos” button.
root = Tk()
- Creates the main Tkinter window.
root.geometry('400x400')
- Sets the size of the main window to 400×400 pixels.
Label(root, text="Youtube Playlist Downloader", font="italic 15 bold").pack(pady=10)
- Adds a label to the main window with the text “Youtube Playlist Downloader” and specified font, with padding of 10 pixels.
Label(root, text="Enter Playlist URL:-", font="italic 10").pack()
- Adds a label to prompt the user to enter the playlist URL, with specified font.
playlistId = Entry(root, width=60)
- Creates an entry widget for the user to input the playlist URL, with a width of 60 characters.
playlistId.pack(pady=5)
- Packs the entry widget into the main window with a padding of 5 pixels.
get_videos = Button(root, text="Get Videos", command=get_list_videos)
- Creates a button labeled “Get Videos” that calls the
get_list_videosfunction when clicked.
get_videos.pack(pady=10)
- Packs the “Get Videos” button into the main window with a padding of 10 pixels.
scrollbar = Scrollbar(root)
- Creates a scrollbar widget.
scrollbar.pack(side=RIGHT, fill=BOTH)
- Packs the scrollbar on the right side of the main window and allows it to fill both horizontal and vertical space.
list_box = Listbox(root, selectmode="multiple")
- Creates a list box widget that allows multiple selections.
list_box.pack(expand=YES, fill="both")
- Packs the list box into the main window, allowing it to expand and fill available space.
list_box.config(yscrollcommand=scrollbar.set)
- Configures the list box to use the scrollbar for vertical scrolling.
scrollbar.config(command=list_box.yview)
- Configures the scrollbar to control the vertical view of the list box.
download_start = Button(root, text="Download Start", command=threading, state=DISABLED)
- Creates a button labeled “Download Start” that calls the
threadingfunction when clicked and is initially disabled.
download_start.pack(pady=10)
- Packs the “Download Start” button into the main window with a padding of 10 pixels.
root.mainloop()
- Starts the Tkinter event loop, allowing the GUI to run and respond to user interactions.
In conclusion, using Python to download YouTube videos or entire playlists is a powerful and efficient way to automate the process. By leveraging libraries such as pyyoutube and pytube, you can easily interact with the YouTube Data API and handle video downloads seamlessly. The provided Tkinter-based GUI application demonstrates how user-friendly interfaces can be created for such tasks, making the process accessible even to those with minimal programming experience. Whether you’re looking to download individual videos or entire playlists, Python offers the tools and flexibility to meet your needs effectively.





Leave a Reply