Build a music player with Tkinter and Pygame in Python
In this tutorial, we will learn how to build or create a simple music player application in Python using Tkinter and Pygame.
Listening to music is a hobby of almost every person you meet around daily, for playing this music we need to have installed a music player in our device, each and every operating system whether it is Windows, Linux, Mac or even Android, Apple IOS also consist of a music player for playing your favorite songs.
So In this tutorial, we will be learning how to create a music player from scratch using the Python Programming Language. As we all know Python has a very rich library support, so from the bunch of libraries we are going to use some of them to build our GUI based music player. The libraries we are going to use are:
- Tkinter – As it is specified in the title of our tutorial that we are going to use the Tkinter library for GUI creation of our music player, as Tkinter is most popular and very easy to use library that comes with many widgets which helps in creating of seamless and nice-looking GUI Applications.
- Pygame – Pygame is also a very library that gives us the power of playing with different multimedia formats like audio, video, etc. In this tutorial, we will be using Pygame’s ‘mixer.music’ module for providing different functionality to are music player application, related to manipulation with the song tracks.
- OS – This is a module that comes in the standard library of Python, we don’t need to install it explicitly. OS provides different functions for interaction with the Operating System. In this tutorial, we are going to use OS for fetching the playlist of songs from the specified directory and make it available to the music player application.
To learn more about Tkinter library, Pygame Library or OS Module of Python you can refer to there documentation.
Building Music Player using Tkinter, Pygame in Python
Before getting started with actual code we need to install the required libraries:
Installation:
$ sudo apt-get install python3-tk $ pip3 install pygame
Now, let’s get started with our code:
Source Code: Music player in Python
# Importing Required Modules & libraries
from tkinter import *
import pygame
import os
# Defining MusicPlayer Class
class MusicPlayer:
# Defining Constructor
def __init__(self,root):
self.root = root
# Title of the window
self.root.title("Music Player")
# Window Geometry
self.root.geometry("1000x200+200+200")
# Initiating Pygame
pygame.init()
# Initiating Pygame Mixer
pygame.mixer.init()
# Declaring track Variable
self.track = StringVar()
# Declaring Status Variable
self.status = StringVar()
# Creating Track Frame for Song label & status label
trackframe = LabelFrame(self.root,text="Song Track",font=("times new roman",15,"bold"),bg="grey",fg="white",bd=5,relief=GROOVE)
trackframe.place(x=0,y=0,width=600,height=100)
# Inserting Song Track Label
songtrack = Label(trackframe,textvariable=self.track,width=20,font=("times new roman",24,"bold"),bg="grey",fg="gold").grid(row=0,column=0,padx=10,pady=5)
# Inserting Status Label
trackstatus = Label(trackframe,textvariable=self.status,font=("times new roman",24,"bold"),bg="grey",fg="gold").grid(row=0,column=1,padx=10,pady=5)
# Creating Button Frame
buttonframe = LabelFrame(self.root,text="Control Panel",font=("times new roman",15,"bold"),bg="grey",fg="white",bd=5,relief=GROOVE)
buttonframe.place(x=0,y=100,width=600,height=100)
# Inserting Play Button
playbtn = Button(buttonframe,text="PLAY",command=self.playsong,width=6,height=1,font=("times new roman",16,"bold"),fg="navyblue",bg="gold").grid(row=0,column=0,padx=10,pady=5)
# Inserting Pause Button
playbtn = Button(buttonframe,text="PAUSE",command=self.pausesong,width=8,height=1,font=("times new roman",16,"bold"),fg="navyblue",bg="gold").grid(row=0,column=1,padx=10,pady=5)
# Inserting Unpause Button
playbtn = Button(buttonframe,text="UNPAUSE",command=self.unpausesong,width=10,height=1,font=("times new roman",16,"bold"),fg="navyblue",bg="gold").grid(row=0,column=2,padx=10,pady=5)
# Inserting Stop Button
playbtn = Button(buttonframe,text="STOP",command=self.stopsong,width=6,height=1,font=("times new roman",16,"bold"),fg="navyblue",bg="gold").grid(row=0,column=3,padx=10,pady=5)
# Creating Playlist Frame
songsframe = LabelFrame(self.root,text="Song Playlist",font=("times new roman",15,"bold"),bg="grey",fg="white",bd=5,relief=GROOVE)
songsframe.place(x=600,y=0,width=400,height=200)
# Inserting scrollbar
scrol_y = Scrollbar(songsframe,orient=VERTICAL)
# Inserting Playlist listbox
self.playlist = Listbox(songsframe,yscrollcommand=scrol_y.set,selectbackground="gold",selectmode=SINGLE,font=("times new roman",12,"bold"),bg="silver",fg="navyblue",bd=5,relief=GROOVE)
# Applying Scrollbar to listbox
scrol_y.pack(side=RIGHT,fill=Y)
scrol_y.config(command=self.playlist.yview)
self.playlist.pack(fill=BOTH)
# Changing Directory for fetching Songs
os.chdir("/home/sameer/Desktop/CodeSpeedy/cs10/songs")
# Fetching Songs
songtracks = os.listdir()
# Inserting Songs into Playlist
for track in songtracks:
self.playlist.insert(END,track)
# Defining Play Song Function
def playsong(self):
# Displaying Selected Song title
self.track.set(self.playlist.get(ACTIVE))
# Displaying Status
self.status.set("-Playing")
# Loading Selected Song
pygame.mixer.music.load(self.playlist.get(ACTIVE))
# Playing Selected Song
pygame.mixer.music.play()
def stopsong(self):
# Displaying Status
self.status.set("-Stopped")
# Stopped Song
pygame.mixer.music.stop()
def pausesong(self):
# Displaying Status
self.status.set("-Paused")
# Paused Song
pygame.mixer.music.pause()
def unpausesong(self):
# Displaying Status
self.status.set("-Playing")
# Playing back Song
pygame.mixer.music.unpause()
# Creating TK Container
root = Tk()
# Passing Root to MusicPlayer Class
MusicPlayer(root)
# Root Window Looping
root.mainloop()I would recommend you to go through the code thoroughly, it is very easy to understand I had also added comments for almost every single line, for making your understanding better.
Output:
Created separate songs directory:

Added Some random songs in the directory:

Started the Music Player Application:

Selecting the song that will be played:

Clicked on the PLAY button, Song Playing:

Clicked on the PAUSE button, Song Paused:

Clicked on the UNPAUSE button, Song Playing:

Clicked on the STOP button, Song Stopped:

So In this way, you can create a simple music player using Python. I hope this tutorial was helpful to you, thank you ‘keep Learning Keep Coding’.
Really wonderful work.. Congratulations
Can you post one with Wx python as well? i couldn’t find one on the internet.
Soon we will publish it
Good work. I have tested the codes with my audio files. When playing the file from musicplayer GUI, the sound changes from the original. How I can play the sound as played in other music players?
While It was happening with me too, but not for all the songs, many of them were playing pretty well and only 1 or 2 were sounding bad. So, the solution to your problem is to use some other library in python for playing audio files, instead of using Pygame.
bro it is showing some error
line 71, in playsong
pygame.mixer.music.load(self.playlist.get(ACTIVE))
pygame.error: Unrecognized audio format
i keep getting this error how can i fix it??
Traceback (most recent call last):
File “C:/Users/Allan/PycharmProjects/untitled1/player.py”, line 86, in
MusicPlayer(root)
File “C:/Users/Allan/PycharmProjects/untitled1/player.py”, line 52, in __init__
os.chdir(“Users\Allan\Desktop\PythonPlayersSong”)
FileNotFoundError: [WinError 3] The system cannot find the path specified: ‘Users\\Allan\\Desktop\\PythonPlayersSong’
pygame.mixer.music.load(self.playlist.get(ACTIVE))
pygame.error: Unrecognized audio format
help
Bro can u send flow chart is this code is running bro bro wt have reports pots and alla send bro..
For an alternative lightweight library to pygame that provides playback functions such as play, pause, resume, seek and volume control, try just_playback. It’s on pypi
please i keep getting this error what should i do
Traceback (most recent call last):
File “C:/Users/lenovo/Desktop/mavins/musicplayer2.py”, line 85, in
MusicPlayer(root)
File “C:/Users/lenovo/Desktop/mavins/musicplayer2.py”, line 45, in __init__
self.playlist = Listbox(songsframe,yscrollcommand=scrol_y.set,selectbackground=”gold”,selectmode=SINGLE,font=(“times new roman”,12,”bold”),bg=”silver”,fg=”navyblue”,bd=5,relief=GROOVE)
NameError: name ‘scrol_y’ is not defined
such a wonderful work everything is on point. The song is playing.