In this lesson we want to learn How to Build Music Player with Python TKinter, Building a simple media player in Python using Tkinter can be achieved by using the ttk.Combobox
and ttk.Button
classes to create a drop-down list for selecting the media files and buttons for controlling the playback. You can use the built-in pygame
library to play the media files. Here is an example of how you might go about building a simple media player in Tkinter:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import tkinter as tk from tkinter import ttk import pygame class MediaPlayer: def __init__(self, root): self.root = root self.root.title("Media Player") self.root.geometry("250x150") self.playlist = ["audio1.mp3", "audio2.mp3", "audio3.mp3"] self.current_track = tk.StringVar() self.current_track.set(self.playlist[0]) self.combobox = ttk.Combobox(self.root, values=self.playlist, textvariable=self.current_track) self.combobox.pack() self.play_button = ttk.Button(self.root, text="Play", command=self.play_track) self.play_button.pack() self.pause_button = ttk.Button(self.root, text="Pause", command=self.pause_track) self.pause_button.pack() self.stop_button = ttk.Button(self.root, text="Stop", command=self.stop_track) self.stop_button.pack() pygame.init() pygame.mixer.init() def play_track(self): pygame.mixer.music.load(self.current_track.get()) pygame.mixer.music.play() def pause_track(self): pygame.mixer.music.pause() def stop_track(self): pygame.mixer.music.stop() if __name__ == "__main__": root = tk.Tk() player = MediaPlayer(root) root.mainloop() |
In this example, we create a MediaPlayer
class that takes the root Tkinter window as a parameter. Then we create a drop-down list ttk.Combobox
which is populated with a list of audio files and a set of buttons ttk.Button
for controlling the playback. The play_track
, pause_track
, and stop_track
methods are used to control the playback of the media files using the pygame
library. You can also add more functionalities like next,previos, volume control, etc. make sure that you have installed pygame.
This is just a basic example, you can customize it as per your requirement.
Learn More on TKinter
- How to Create Conutdown Timer with Python & TKinter
- Create GUI Applications with Python & TKinter
- Python TKinter Layout Management
- How to Create Label in TKinter
- How to Create Buttin in Python TKinter
Run the complete code and this is the result.
