Python Music Player Tutorial: Build with Tkinter & Pygame
To create a versatile music player, you can use the Tkinter library in Python to create the graphical user interface and the pygame library to implement the music playing functionality. Below is a simple example code:
import os
import tkinter as tk
from tkinter import filedialog
import pygame
class MusicPlayer:
def __init__(self, root):
self.root = root
self.root.title("Music Player")
self.playlist = []
self.current_index = 0
self.create_widgets()
pygame.init()
def create_widgets(self):
self.play_button = tk.Button(self.root, text="Play", command=self.play_music)
self.play_button.pack()
self.pause_button = tk.Button(self.root, text="Pause", command=self.pause_music)
self.pause_button.pack()
self.stop_button = tk.Button(self.root, text="Stop", command=self.stop_music)
self.stop_button.pack()
self.add_button = tk.Button(self.root, text="Add Music", command=self.add_music)
self.add_button.pack()
def play_music(self):
pygame.mixer.music.load(self.playlist[self.current_index])
pygame.mixer.music.play()
def pause_music(self):
pygame.mixer.music.pause()
def stop_music(self):
pygame.mixer.music.stop()
def add_music(self):
file_path = filedialog.askopenfilename(filetypes=[("Music files", "*.mp3")])
if file_path:
self.playlist.append(file_path)
if __name__ == "__main__":
root = tk.Tk()
app = MusicPlayer(root)
root.mainloop()
This sample code creates a basic music player that can play, pause, stop music, and add music files to a playlist. You can customize and enhance this player according to your own needs.