The Wayback Machine - https://web.archive.org/web/20240930185342/https://www.geeksforgeeks.org/create-gui-for-downloading-youtube-video-using-python/
Open In App

Create GUI for Downloading Youtube Video using Python

Last Updated : 11 Dec, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisites: Python GUI – tkinter

YouTube is a very popular video-sharing website. Downloading a video’s/playlist from YouTube is a tedious task. Downloading that video through Downloader or trying to download it from a random website increase’s the risk of licking your personal data. Using the Python Tkinter package, this task is very simple-efficient-safe. Few bunch codes will download the video for you. For this, there are two Python libraries – Tkinter and pytube. 
 

Modules Required:

  • pytube :pytube is a lightweight, simple-to-use, dependency-free Python library that is used for downloading videos from the web.pytube, is not an auto-configured library. You need to install it before using it. Installation of pytube is easy when you have pip. In the Terminal or Command Prompt, type the following command to install pytube.
    If you are on Mac OS X or Linux, chances are that one of the following two commands will work for you:

pip install pytube 
git clone git://github.com/NFicano/pytube.git pytube | cd pytube | python setup.py install

  • If you are on Window’s 
pip install pytube3
  • Tkinter: Tkinter is a Python binding to the Tk GUI toolkit. It is the standard Python interface to the Tk GUI toolkit or in simple words Tkinter is used as a Python Graphical User interface. Tkinter is the native library, you don’t need to install it externally, just import, while you use it.

Below is the implementation.

Python3




# Importing necessary packages
import tkinter as tk
from tkinter import *
from pytube import YouTube
from tkinter import messagebox, filedialog
 
 
# Defining CreateWidgets() function
# to create necessary tkinter widgets
def Widgets():
 
    head_label = Label(root, text="YouTube Video Downloader Using Tkinter",
                       padx=15,
                       pady=15,
                       font="SegoeUI 14",
                       bg="palegreen1",
                       fg="red")
    head_label.grid(row=1,
                    column=1,
                    pady=10,
                    padx=5,
                    columnspan=3)
 
    link_label = Label(root,
                       text="YouTube link :",
                       bg="salmon",
                       pady=5,
                       padx=5)
    link_label.grid(row=2,
                    column=0,
                    pady=5,
                    padx=5)
 
    root.linkText = Entry(root,
                          width=35,
                          textvariable=video_Link,
                          font="Arial 14")
    root.linkText.grid(row=2,
                       column=1,
                       pady=5,
                       padx=5,
                       columnspan=2)
 
 
    destination_label = Label(root,
                              text="Destination :",
                              bg="salmon",
                              pady=5,
                              padx=9)
    destination_label.grid(row=3,
                           column=0,
                           pady=5,
                           padx=5)
 
 
    root.destinationText = Entry(root,
                                 width=27,
                                 textvariable=download_Path,
                                 font="Arial 14")
    root.destinationText.grid(row=3,
                              column=1,
                              pady=5,
                              padx=5)
 
 
    browse_B = Button(root,
                      text="Browse",
                      command=Browse,
                      width=10,
                      bg="bisque",
                      relief=GROOVE)
    browse_B.grid(row=3,
                  column=2,
                  pady=1,
                  padx=1)
 
    Download_B = Button(root,
                        text="Download Video",
                        command=Download,
                        width=20,
                        bg="thistle1",
                        pady=10,
                        padx=15,
                        relief=GROOVE,
                        font="Georgia, 13")
    Download_B.grid(row=4,
                    column=1,
                    pady=20,
                    padx=20)
 
 
# Defining Browse() to select a
# destination folder to save the video
 
def Browse():
    # Presenting user with a pop-up for
    # directory selection. initialdir
    # argument is optional Retrieving the
    # user-input destination directory and
    # storing it in downloadDirectory
    download_Directory = filedialog.askdirectory(
        initialdir="YOUR DIRECTORY PATH", title="Save Video")
 
    # Displaying the directory in the directory
    # textbox
    download_Path.set(download_Directory)
 
# Defining Download() to download the video
 
 
def Download():
 
    # getting user-input Youtube Link
    Youtube_link = video_Link.get()
 
    # select the optimal location for
    # saving file's
    download_Folder = download_Path.get()
 
    # Creating object of YouTube()
    getVideo = YouTube(Youtube_link)
 
    # Getting all the available streams of the
    # youtube video and selecting the first
    # from the
    videoStream = getVideo.streams.first()
 
    # Downloading the video to destination
    # directory
    videoStream.download(download_Folder)
 
    # Displaying the message
    messagebox.showinfo("SUCCESSFULLY",
                        "DOWNLOADED AND SAVED IN\n"
                        + download_Folder)
 
 
# Creating object of tk class
root = tk.Tk()
 
# Setting the title, background color
# and size of the tkinter window and
# disabling the resizing property
root.geometry("520x280")
root.resizable(False, False)
root.title("YouTube Video Downloader")
root.config(background="PaleGreen1")
 
# Creating the tkinter Variables
video_Link = StringVar()
download_Path = StringVar()
 
# Calling the Widgets() function
Widgets()
 
# Defining infinite loop to run
# application
root.mainloop()


Output:

Code Explanation:

  1. The code starts by importing the required modules.
  2. The first module is tkinter, which provides the basic functionality for creating graphical user interfaces (GUIs).
  3. Next, the tkinter module helps create a Progressbar object.
  4. This object displays the progress of an operation or task.
  5. Finally, time is imported to help calculate how long it has been since the last sleep command was executed.
  6. Next, the intro class is created.
  7. The _init_() method is used to initialize the class variables and also open a hidden window.
  8. The wind variable stores information about the current window’s position and size onscreen.
  9. The resize() method allows you to change these values without closing or reopening the window.
  10. The next line of code uses the deiconify() function to hide the main window and then calls resizable() to make sure that it remains invisible while still allowing users to resize it as needed.
  11. The code firstly creates an instance of the intro class.
  12. This class will be used to display information about the app and its features.
  13. Next, the _init_() method is called.
  14. This method is used to initialize the class variables and also to open a hidden window.
  15. The hidden window will be used to display information about the app and its features.
  16. The last part of this code is used to resize the hidden window if needed.
  17. The code starts by creating a new GeeksforGeeks Unit Converter window.
  18. The window has a label (wind) and a background color (#008080).
  19. The text in the label is “Welcome to GeeksforGeeks Unit Converter!”
  20. The next line of code creates a Label object named entry.
  21. The entry object has the following properties: • x position (50, 30), • y position (30, 50), • width (410, 30), and • height (30).
  22. Next, the code sets up the load bar.
  23. This bar will show how much progress is being made in converting units.
  24. The bar has an orientation property of HORIZONTAL and a length property of 250 pixels.
  25. The mode property is set to “indeterminate.”
  26. This means that the progressbar will not display any specific values but will instead remain in an indeterminate state until it is clicked or interacted with.
  27. Finally, the code creates an Analyze() function which will be used later on to perform unit conversions.
  28. The code creates a Label object called entry and sets the text to “Welcome to GeeksforGeeks Unit Converter!”.
  29. The label is then placed at (x=50,y=30) with a width of 410 pixels and a height of 30 pixels.
  30. Next, the code creates a Progressbar object and sets its orientation to be HORIZONTAL.
  31. The progress bar’s length is set to 250 pixels and its mode is set to “indeterminate”.
  32. Finally, the code loads the GeeksforGeeks Unit Converter module onto the screen.
  33. The code starts with a self.start button.
  34. This button opens the converter window.
  35. Next, there is a follow label.
  36. The follow label has the same background color as the start button and has white text on a blue background.
  37. The text says “Follow Me On.”
  38. The next part of the code creates two buttons: self.start and follow.
  39. The self.start button is black with a white text box that says “START.”
  40. The follow button is blue with white text that says “Follow Me On.”
  41. Finally, the code sets up how these buttons will look onscreen by setting their widths and heights.
  42. The code creates a start button and a follow me label.
  43. The start button will open the converter window, while the follow me label will display the text “Follow Me On.”
  44. The code starts with a self.git variable that stores the image of your GitHub profile.
  45. Next, there are three buttons: one for Instagram, one for Facebook, and one for Twitter.
  46. The code to create each button is very simple.
  47. The first line creates a PhotoImage object and assigns it to the self.instag variable.
  48. The second line creates a Button object and assigns it to the self.fcb variable.
  49. Finally, the third line places each button on the screen at (x=190, y=190), (x=110, y=190), and (x=350, y=190), respectively.
  50. When you run this program, you’ll see three buttons on your screen: one for GitHub, one for Instagram, and one for Facebook.
  51. To use these buttons in your code, you need to add some code to handle user input.
  52. In this example, all three buttons have command properties that allow you to execute arbitrary Python commands when the user clicks on them.
  53. For example: self.instag.command(“upload_image”) This will upload an image from your computer’s hard drive to Instagram using the Instagram API!
  54. The code will create a toolbar at the top of your document that includes buttons for GitHub, Instagram, Facebook, and Twitter.
  55. The buttons will be placed at (x=186, y=150), (x=110, y=190), (x=350, y=190), and (x=-10, y=190).
  56. The width and height of each button will be 30 pixels.
  57. The command attribute of each button will contain a lambda function that will open the corresponding link in a new tab or window.
  58. The code first opens the Google Chrome browser.
  59. It then uses the links() function to open the author’s website in a new tab.
  60. The loading() function displays a ProgressBar while the website is being loaded.
  61. Finally, the start() and load() functions are used to position and display the buttons, respectively.
  62. The code will open the link in a new browser window and load the progress bar.
  63. 3:49 PM, 11/30/2022] Ankit Kumar: The code in this function creates the necessary widgets for downloading a YouTube video.
  64. The first widget is a label called “head_label.”
  65. This label will be used to display the name of the video being downloaded.
  66. The second widget is a Label called “video_label.”
  67. This label will be used to display the filename of the video being downloaded.
  68. The third widget is a Button called “download.”
  69. This button will be used to start downloading the video.
  70. The next line of code defines two variables: “filepath” and “duration.”
  71. These variables will store information about the file that is being downloaded.
  72. The filepath variable will store the full path to the file that is being downloaded.
  73. The duration variable will store how long it has been since the last time this file was updated (in seconds).
  74. The next line of code creates an instance of FileDialog().
  75. This object allows users to select files from their computer.
  76. In this case, we are asking users to select a file from their hard drive.
  77. Next, we create an instance of Tkinter’s MessageBox() object.
  78. This object allows us to display messages onscreen.
  79. We use this object to ask users if they want to download the video or not.
  80. Finally, we create an instance
  81. The code creates a function called Widgets().
  82. This function will be used to create the necessary tkinter widgets needed for our YouTube video downloader.
  83. First, we create a Label widget called head_label.
  84. This label will be used to display the title of our YouTube video downloader.
  85. We also specify that this label should have a width of 15 pixels and a height of 15 pixels.
  86. Next, we create a Button widget called DownloadButton.
  87. This button will be used to initiate the download process for our YouTube video.
  88. We specify that this button should have a width of 25 pixels and a height of 20 pixels.
  89. Finally, we create a FileDialog widget called FileDialog1.
  90. This file dialog will be used to allow the
  91. The code starts with a head_label and link_label.
  92. The head_label has a grid that will have three rows and three columns.
  93. The first row is the column number, the second row is the column width, and the third row is the column span.
  94. The link_label has a grid that will have two rows and two columns.
  95. The first row is the column number, and the second row is the column width.
  96. The link_label also has a pady value of 5, which means it will take up five pixels in each direction on each line of its grid.
  97. Next, there are two root objects created: one for the head_label and one for the link_label.
  98. Next, text variables are set for both objects: video_Link for the head_label’s text variable and download_Path for the link_labels text variable.
  99. These variables can be edited later if needed.
  100. Then buttons are created: browse_B with a command of Browse and Download B with a command of Download Video.
  101. Both buttons have grids that specify their dimensions (width x height), background colors (bisque for Browse and thistle1 for Download Video), relief values (GROOVE), as well as button
  102. The code creates a simple two-column layout with a heading and two labels.
  103. The heading has a grid that lays out the row and column values for each label.
  104. The first label, link_label, is the text that will be displayed on the YouTube link heading.
  105. The second label, destination_label, is the text that will be displayed on the destination heading.
  106. The root object contains all of the content for the layout.
  107. The first entry in this object is for the width of the video link heading.
  108. This value is set to 35 pixels wide.
  109. Next, there is a textvariable attribute which stores the actual text that will be displayed in this heading.
  110. In this case, it’s video_Link.
  111. Finally, font and color are
  112. The code begins by defining a function, Browse().
  113. The function takes one argument, initialdir.
  114. If initialdir is not provided, the program will use the current working directory as the destination folder for saving the video.
  115. Next, the code retrieves the user’s input destination directory using filedialog.askdirectory().
  116. This function returns a string value that represents the user’s selection.
  117. The code stores this value in downloadDirectory.
  118. The final part of the code defines and calls Browse() with initialdir as its only argument.
  119. When Browse() is called, it will first present a pop-up window asking the user to select a destination folder for saving their video.
  120. If initialdir is provided, it will be used as the source folder for downloading and saving the video in that location.
  121. Otherwise, if initialdir is not provided, then the program will use the current working directory as its source folder for downloading and saving videos
  122. The code first defines a function called Browse().
  123. This function will be used to select a destination folder for saving the video.
  124. The Browse() function takes two arguments: initialdir and optional retriveDir.
  125. The initialdir argument is optional, and if left blank, the program will use the current working directory as the destination folder.
  126. RetrieveDir is an optional argument and if left blank, the program will use the current user’s default download location.
  127. Once the destination folder has been selected, the code stores it in downloadDirectory.
  128. Next, a file dialog is displayed asking the user to input a filename for saving the video.
  129. The user’s input is stored in filename.
  130. Finally, Browse() returns True if successful or False if there was an error.


Previous Article
Next Article

Similar Reads

GUI to get views, likes, and title of a YouTube video using YouTube API in Python
Prerequisite: YouTube API, Tkinter Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. In this art
2 min read
Python - Downloading captions from YouTube
Python provides a large set of APIs for the developer to choose from. Each and every service provided by Google has an associated API. Being one of them, YouTube Transcript API is very simple to use provides various features. In this article, we will learn how to download captions or subtitles from a YouTube video. The subtitles can be auto-generat
6 min read
How to Extract YouTube Comments Using Youtube API - Python
Prerequisite: YouTube API Google provides a large set of API’s for the developer to choose from. Each and every service provided by Google has an associated API. Being one of them, YouTube Data API is very simple to use provides features like – Search for videosHandle videos like retrieve information about a video, insert a video, delete a video et
2 min read
Downloading PDFs with Python using Requests and BeautifulSoup
BeautifulSoup object is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. The BeautifulSoup object represents the parsed document as a whole. For most purposes, you can treat it as a Tag object. Requests library i
2 min read
Downloading files from web using Python
Requests is a versatile HTTP library in python with various applications. One of its applications is to download a file from web using the file URL. Installation: First of all, you would need to download the requests library. You can directly install it using pip by typing following command: pip install requests Or download it directly from here an
4 min read
Python - Obtain title, views and likes of YouTube video using BeautifulSoup
In this article, we will learn how can we obtain data (like title, views, likes, dislikes etc) from any YouTube video using a Python script. For this task, we are going to use very famous library for web scraping BeautifulSoup and Requests. Modules required and Installation : Requests : Requests allows you to send HTTP/1.1 requests extremely easily
2 min read
Playing Youtube Video using Python
In this article, we will see how we can play youtube video in python. In order to play youtube videos in python we need pafy and vlc module. Pafy is a Python library to download YouTube content and retrieve metadata. Below is the command to install pafy pip install pafy VLC : is a python library to use the functionality of the vlc media player. In
2 min read
PyQt5 - How to automate Progress Bar while downloading using urllib?
PyQt5 is one of the emerging GUI libraries in terms of developing Python GUI Desktop apps. It has rich and robust functionality which ensures production quality apps. Learning PyQt5 library is an add-on to your knowledge. You can develop your consumer quality, highly professional apps. In this article, we will learn how to automate the Progress Bar
3 min read
Youtube video downloader using Django
In this article, we will see how to make a YouTube video downloader tool in Django. We will be using pytube module for that. Prerequisite: pytube: It is python's lightweight and dependency-free module, which is used to download YouTube Videos.Django: It is python's framework to make web-applications. Here, we will be using Django as a backend along
2 min read
Download Youtube Video(s) or whole Playlist with Python
Prerequisite: Tkinterpyyoutubepytubethreading in TkinterYouTube API Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to cre
6 min read
Extract Video Titles with the Youtube API in Python
Extracting video titles from YouTube can be incredibly useful for various applications, such as data analysis, content creation, and trend tracking. The YouTube Data API provides a robust way to interact with YouTube's platform and extract this information. This guide will walk you through the process of extracting video titles using the YouTube AP
4 min read
Pafy - Downloading Stream
In this article we will see how we can download given youtube video stream in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. Stream is basically available resolution of video is available on youtube. Downloaded file get saved in th
2 min read
Uploading and Downloading Files in Flask
This article will go over how to upload and download files using a Flask database using Python. Basically, we have a section for uploading files where we can upload files that will automatically save in our database. When we upload a file and submit it, a message stating that your file has been uploaded and displaying the file name on the screen ap
7 min read
Python | Create a GUI Marksheet using Tkinter
Create a python GUI mark sheet. Where credits of each subject are given, enter the grades obtained in each subject and click on Submit. The credits per subject, the total credits as well as the SGPA are displayed after being calculated automatically. Use Tkinter to create the GUI interface. Refer the below articles to get the idea about basics of t
8 min read
Create Copy-Move GUI using Tkinter in Python
Everyone reading this post is well aware of the importance of Copying the file or moving the file from one specific location to another. In this post, we have tried to explain not only the program but added some exciting pieces of Interface. Up to now, many of you may get about what we are talking about. Yes, you are right, We are going to use "Tki
4 min read
Create a GUI to get Sunset and Sunrise time using Python.
Prerequisite: Tkinter module In this article, we are going to write python scripts to get sunset and sunrise time and bind it with the GUI application. Before starting we need to understand suntime and geopy module Modules Needed: suntime module: This module will return the sunset and sunrise time calculation python library. Run this command in you
3 min read
Create a GUI to Extract information from VIN number Using Python
Prerequisite: Python GUI – tkinter In this article, we are going to look at how can we use Python to extract vehicle information from its VIN number (Vehicle Identification Number). A VIN consists of 17 characters (digits and capital letters) that act as a unique identifier for the vehicle. It is a unique code that is assigned to every motor vehicl
3 min read
Create a GUI to search bank information with IFSC Code using Python
Prerequisite: Python GUI – tkinter The following program depicts how a GUI application can be formulated using python script to get bank details by using IFSC code. Here, we are using Razorpay IFSC Toolkit to fetch IFSC code. Razorpay IFSC Toolkit processes IFSC codes via their toolkit and return data set. Module Needed: requests Requests allows yo
3 min read
Create a GUI to extract Lyrics from song Using Python
In this article, we are going to write a python script to extract lyrics from the song and bind with its GUI application. We will use lyrics-extractor to get lyrics of a song just by passing in the song name, it extracts and returns the song's title and song lyrics from various websites. Before starting, install the lyrics-extractor module. Run thi
3 min read
Create First GUI Application using Python-Tkinter
We are now stepping into making applications with graphical elements, we will learn how to make cool apps and focus more on its GUI(Graphical User Interface) using Tkinter. What is Tkinter?Tkinter is a Python Package for creating GUI applications. Python has a lot of GUI frameworks, but Tkinter is the only framework that’s built into the Python sta
12 min read
Create a GUI to find the IP for Domain names using Python
Prerequisite: Python GUI – tkinter In this article, we are going to see how to find IP from Domain Names and bind it with GUI Application using Python. We will use iplookup module for looking up IP from Domain Names. It is a small module which accepts a single domain as a string, or multiple domains as a list, and returns a list of associated IP. R
2 min read
Create a GUI to check Domain Availability using Tkinter
There might be a case where a user wants to create a website and having certain ideas for the website's name but is struck on their availability. So let's develop a GUI that will check for domain availability. We will use the Python-whois module to get information about the website. It's able to extract data for all the popular TLDs (com, org, net,
2 min read
Create a GUI to Get Domain Information Using Tkinter
Prerequisites: Python GUI – tkinter Domain information is very important for every user. It contains information like Name, organization, State, city, Ip address, emails, server name, etc. In this article, we will write code for getting domain information and bind it with GUI Application. We will use the Python-whois module to get information about
2 min read
How to Create GUI Applications Under Linux Desktop Using PyGObject
The creation of applications in Linux can be done through various methods. But, the most efficient way of creating a GUI application in Linux can be done through PyGObject in Python. PyGObject is the next generation from the PyGTK library in Python, we can say that PyGObject = Python + GTK3. So, in this article, we will be creating a GUI applicatio
6 min read
Create GUI to Web Scrape articles in Python
Prerequisite- GUI Application using Tkinter In this article, we are going to write scripts to extract information from the article in the given URL. Information like Title, Meta information, Articles Description, etc., will be extracted. We are going to use Goose Module. Goose module helps to extract the following information: The main text of an a
2 min read
How to create a COVID19 Data Representation GUI?
Prerequisites: Python Requests, Python GUI – tkinterSometimes we just want a quick fast tool to really tell whats the current update, we just need a bare minimum of data. Web scraping deals with taking some data from the web and then processing it and displaying the relevant content in a short and crisp manner. What the code is doing ? First we are
2 min read
Python | Create video using multiple images using OpenCV
As we know OpenCV is a widely used library for image processing. It provides a wide sense of image processing. Let's see how to create video using multiple images using OpenCV. Install the following libraries: PIL cv2 Also, check the path before running the code otherwise you will be full with errors. How it works ? Using PIL library we are opening
3 min read
Pafy - Getting Video ID of the given Video
In this article we will see how we can get video ID of the given youtube video in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. A Youtube Video ID is an unique ID to identify a video which is uploaded to Youtube. The Youtube video
2 min read
Pafy - Getting Best Video Stream of the given Video
In this article we will see how we can get best video stream of the given youtube video in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. Best video stream is basically a video stream which is available and in highest resolution. T
2 min read
Using lambda in GUI programs in Python
Python Lambda Functions are anonymous function means that the function is without a name. In this article, we will learn to use lambda functions in Tkinter GUI. We use lambda functions to write our code more efficiently and to use one function many times by passing different arguments. We use the lambda function to pass arguments to other functions
3 min read
Practice Tags :