Build a Music Player with Tkinter and Pygame in Python
Last Updated :
03 Apr, 2025
We all use music players like Windows Media Player or VLC to play music on our system. Have you ever wanted to create your own music player if your answer is yes then with Python, you can build a customized Music Player. In this article, you will see how to build a simple yet functional music player using two powerful Python libraries: Tkinter and Pygame. Tkinter will help us create the graphical user interface (GUI), while Pygame will handle the music playback. Even if you have never used Python before and you know nothing about it, no need to worry. as this article will guide you through each step one by one, and by the end, you'll have a music player that can load, play, pause, and navigate through the playlist of your favorite songs. So, let's dive in and start making some music!
Music Player with Tkinter and Pygame in Python
Here, for creating the Music Player App Using Python follow the below steps
Create the Virtual Environment
using the below command create virtual environment
python -m venv env
.\env\Scripts\activate.ps1
Project Structure Install Nesseaccary Libraries
To install the required libraries, Tkinter and Pygame, use the following commands:
pip install tk
pip install pygame
pip install requests
These commands will install the necessary dependencies for utilizing Tkinter and Pygame in your Python environment
Import Necessary libraries
First, import the Tkinter ,Pygame , os and requests library in the following manner to create the GUI, handle the music playback , to interact with the operating system to list MP3 files in a directory and to download the icons from weblinks.
import requests
from tkinter import filedialog, Tk, Menu, Listbox, Button, Frame, PhotoImage, END
import pygame
import os
Code Implementation
app.py: This Python code creates a simple music player using Tkinter and Pygame. Tkinter helps make the buttons and lists you see on the screen, while Pygame plays the music.
First, the app sets up a window with a title, size, and icon. Then, Pygame is initialized to handle playing music and to check when a song finishes. A menu is added to the window, letting you pick a folder that contains your music files. This way, you can load all your songs into the player. Some global variables keep track of your playlist, the current song playing, and whether the music is paused. The app has different functions to handle various tasks:
- load_music(): Opens a dialog for you to choose a folder and loads all MP3 songs from that folder into the playlist.
- play_music(): Plays the song you select or resumes playing if the music was paused.
- pause_music(): Pauses the song that is currently playing.
- next_song(): Plays the next song in the playlist.
- previous_song(): Plays the previous song in the playlist.
- check_music_end(): Automatically plays the next song when the current one finishes.
The app's interface includes a list that shows all the songs in your playlist and buttons to play, pause, go to the next song, or go to the previous song. When you select a song from the list, it starts playing. The app also keeps checking if a song has ended to play the next one automatically.
This code makes a straightforward music player that lets you easily manage and listen to your favorite songs.
Python
# Import necessary modules
import requests
from tkinter import filedialog, Tk, Menu, Listbox, Button, Frame, PhotoImage, END
import pygame
import os
# Download the image from the web
def download_image(image_url,file_name):
response = requests.get(image_url)
with open(file_name, 'wb') as file:
file.write(response.content)
download_image('https://media.geeksforgeeks.org/wp-content/uploads/20240610151925/background.png','background.png')
download_image('https://media.geeksforgeeks.org/wp-content/uploads/20240610151926/next.png','next.png')
download_image('https://media.geeksforgeeks.org/wp-content/uploads/20240610151926/pause.png','pause.png')
download_image('https://media.geeksforgeeks.org/wp-content/uploads/20240610151926/play.png','play.png')
download_image('https://media.geeksforgeeks.org/wp-content/uploads/20240610151926/previous.png','previous.png')
# Initialize the Tkinter window
app = Tk()
app.title('Music Player with Tkinter and Pygame in Python')
app.geometry("500x300")
# Change the application icon
app_icon = PhotoImage(file='background.png')
app.iconphoto(False, app_icon)
# Initialize Pygame's mixer module for playing audio
pygame.mixer.init()
# Define an event for when a song ends
SONG_END_EVENT = pygame.USEREVENT + 1
pygame.mixer.music.set_endevent(SONG_END_EVENT)
# Create a menu bar
menu_bar = Menu(app)
app.config(menu=menu_bar)
# Define global variables
playlist = [] # List to store names of songs
current_song = "" # Store the currently playing song
is_paused = False # Flag to indicate if music is paused
# Function to load music from a directory
def load_music():
global current_song
app.directory = filedialog.askdirectory()
# Clear the current list of songs
playlist.clear()
song_listbox.delete(0, END)
# Iterate through files in the directory and add MP3 files to the playlist
for file in os.listdir(app.directory):
name, ext = os.path.splitext(file)
if ext == '.mp3':
playlist.append(file)
# Add songs to the listbox
for song in playlist:
song_listbox.insert("end", song)
# Select the first song in the list by default, if there are any songs
if playlist:
song_listbox.selection_set(0)
current_song = playlist[song_listbox.curselection()[0]]
# Function to play music
def play_music(event=None):
global current_song, is_paused
if not playlist:
return
# Get the selected song from the listbox
current_selection = song_listbox.curselection()
if current_selection:
current_song = playlist[current_selection[0]]
# If not paused, load and play the current song
if not is_paused:
pygame.mixer.music.load(os.path.join(app.directory, current_song))
pygame.mixer.music.play()
else:
# If paused, unpause the music
pygame.mixer.music.unpause()
is_paused = False
# Function to pause music
def pause_music():
global is_paused
if not playlist:
return
pygame.mixer.music.pause()
is_paused = True
# Function to play the next song
def next_song():
global current_song, is_paused
if not playlist:
return
try:
# Clear previous selection and select the next song in the list
song_listbox.selection_clear(0, END)
next_index = (playlist.index(current_song) + 1) % len(playlist)
song_listbox.selection_set(next_index)
current_song = playlist[song_listbox.curselection()[0]]
is_paused = False # Reset paused flag for next song
play_music()
except:
pass
# Function to play the previous song
def previous_song():
global current_song, is_paused
if not playlist:
return
try:
# Clear previous selection and select the previous song in the list
song_listbox.selection_clear(0, END)
prev_index = (playlist.index(current_song) - 1) % len(playlist)
song_listbox.selection_set(prev_index)
current_song = playlist[song_listbox.curselection()[0]]
is_paused = False # Reset paused flag for previous song
play_music()
except:
pass
# Function to check if the music has ended
def check_music_end():
if not pygame.mixer.music.get_busy() and not is_paused and playlist:
next_song()
app.after(100, check_music_end)
# Create a menu for adding songs
add_songs_menu = Menu(menu_bar, tearoff=False)
add_songs_menu.add_command(label='Select Folder', command=load_music)
menu_bar.add_cascade(label='Add Songs', menu=add_songs_menu)
# Create a listbox to display songs
song_listbox = Listbox(app, bg="green", fg="white", width=100, height=13)
song_listbox.pack()
# Bind a selection event to the listbox
song_listbox.bind("<<ListboxSelect>>", play_music)
# Load images for control buttons
play_button_image = PhotoImage(file='play.png')
pause_button_image = PhotoImage(file='pause.png')
next_button_image = PhotoImage(file='next.png')
previous_button_image = PhotoImage(file='previous.png')
# Create control buttons
control_frame = Frame(app)
control_frame.pack()
play_button = Button(control_frame, image=play_button_image, borderwidth=0, command=play_music)
pause_button = Button(control_frame, image=pause_button_image, borderwidth=0, command=pause_music)
next_button = Button(control_frame, image=next_button_image, borderwidth=0, command=next_song)
previous_button = Button(control_frame, image=previous_button_image, borderwidth=0, command=previous_song)
# Arrange control buttons
previous_button.grid(row=0, column=0, padx=5)
play_button.grid(row=0, column=1, padx=5)
pause_button.grid(row=0, column=2, padx=5)
next_button.grid(row=0, column=3, padx=5)
# Start checking for the end of song event
app.after(100, check_music_end)
# Start Tkinter event loop
app.mainloop()
#This code is contributed by sourabh_jain
Output
Music Player App with Tkinter and Pygame in PythonVideo Demonstration
Conclusion
In conclusion, the Music Player App created using Python combines the Tkinter and Pygame libraries to offer a straightforward and user-friendly interface for playing music files. This app allows users to load a folder of MP3 songs, play, pause, and navigate through their music collection effortlessly. By integrating Pygame for audio playback and Tkinter for the graphical interface, the app provides a simple yet effective solution for music enthusiasts. The ability to select songs from a list, along with intuitive control buttons, ensures an enjoyable listening experience. This Music Player App is a practical and accessible tool for anyone looking to manage and enjoy their music library with ease.
Similar Reads
Python Tkinter | Create LabelFrame and add widgets to it Tkinter is a Python module which is used to create GUI (Graphical User Interface) applications. It is a widely used module which comes along with the Python. It consists of various types of widgets which can be used to make GUI more user-friendly and attractive as well as functionality can be increa
2 min read
Create a "Play Again" Option with Python Pygame Adding a "Play Again" feature to your Snake game using Python's Pygame module involves several steps.Game Variables Reset: restart_game method resets the snake, food, direction, and game over flag.Game Over Display: show_game_over method displays a message and a button to restart the game.Event Bind
6 min read
How to create MS Paint clone with Python and PyGame? In this article, we will create a simple MS paint program with Python and PyGame. MS Paint is a simple program made by Microsoft, it allows users to create basic art and painting. Since its inception, MS Paint has been included with every version of Microsoft Windows. MS Paint provides features for
9 min read
Python | Display images with PyGame Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, itâs up to the imagination or necessity of the developer, what type of game he/she wants to develop usin
2 min read
Python | Playing audio file in Pygame Game programming is very rewarding nowadays and it can also be used in advertising and as a teaching tool too. Game development includes mathematics, logic, physics, AI and much more and it can be amazingly fun. In python, game programming is done in pygame and it is one of the best modules for doin
2 min read