skip to Main Content

I am a new user of python who started last week. I am creating a music library or music player as one of my school assignments that allows users to click on the arrows to skip to the next song as long as it’s in the same file. However, one problem! The GUI looks terrible and super boring. I have 2 questions today:

  1. How do I change the background image of this whole layout and photoshop my own images in the background to add to the excitement? What I am hoping to do in the end is have a video playing in the massive space as well, a preferred video so they’d at least have something nice to watch as they listen to their selected songs.

Here’s what the silly thing looks like:

enter image description here

Here’s the code:

#     GUI     #
import tkinter as tk
from tkinter import *
from tkinter import filedialog


#     AUDIO   #
from pygame import mixer

#     DIRECTORY NAVIGATION   #
from os import walk

#     EXCEPTION HANDLER   #
import pygame

#     VOLUME CONTROL   #
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume, ISimpleAudioVolume
from ctypes import cast, POINTER
# YOU MIGHT NEED TO PIP INSTALL THESE
# IF THOSE DONT WORK TRY
# py -m pip install [library]
# pip install pycaw
# pip install comtypes
# pip install psutil



class MP:
    
    def __init__(self, win):
        # Create Tkinter window
        win.geometry('600x300')
        win.title('Jared AIT Music Player')
        win.resizable(0, 0)
 

        # StringVar to change button text later
        self.play_restart = tk.StringVar()
        self.pause_resume = tk.StringVar()
        self.play_restart.set('Play')
        self.pause_resume.set('Pause')

        # The buttons and their positions
        load_button = Button(win, text='Load', width=10, font=("Arial", 10), command=self.load)
        load_button.place(x=50,y=250, anchor='center')

        play_button = Button(win, textvariable=self.play_restart, width=10, font=("Arial", 10), command=self.play)
        play_button.place(x=150,y=250, anchor='center')

        pause_button = Button(win, textvariable=self.pause_resume, width=10, font=("Arial", 10), command=self.pause)
        pause_button.place(x=250,y=250, anchor='center')

        stop_button = Button(win, text="Stop", width=10, font=("Arial", 10), command=self.stop)
        stop_button.place(x=350,y=250, anchor='center')

        next_button = Button(win ,text = '>>',  width = 10, font = ('Arial', 10), command = self.next)
        next_button.place(x=550,y=250, anchor='center')

        back_button = Button(win ,text = '<<',  width = 10, font = ('Arial', 10), command = self.back)
        back_button.place(x=450,y=250, anchor='center')

        #SLIDERS
        volume_slider = Scale(win, from_=100, to=0, orient=VERTICAL, command=self.volume, length=125)
        volume_slider.grid(row=0, column=1)



 
 

        self.music_file = False
        self.playing_state = False

        
    def volume(self,volume_level):
        #       THIS INITIALISES THE VOLUME CONTROL     #
        devices = AudioUtilities.GetSpeakers()
        interface = devices.Activate(
        IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
        volume = cast(interface, POINTER(IAudioEndpointVolume))

        #       THIS SETS THE VOLUME    #
        volume.SetMasterVolumeLevelScalar(int(volume_level)/100, None)

        

    def load(self):
        self.music_file = filedialog.askopenfilename(initialdir="/AIT Python 1/Assets", title="Select a song", filetypes=(("wav files", "*.wav"),("all files", "*.*"),("mp3 files", "*.mp3")))
        print("Loaded:", self.music_file)
        self.play_restart.set('Play')

    


    def play(self):
        if self.music_file:
            mixer.init()
            mixer.music.load(self.music_file)
            mixer.music.play()
            self.playing_state = False
            self.play_restart.set('Restart')
            self.pause_resume.set('Pause')

    def pause(self):
        if not self.playing_state:
            mixer.music.pause()
            self.playing_state = True
            self.pause_resume.set('Resume')
        else:
            mixer.music.unpause()
            self.playing_state = False
            self.pause_resume.set('Pause')

    def stop(self):
        mixer.music.stop()

    ########################################################################################################       
    def next(self):
        self.file_path = (self.music_file.rsplit("/",1))[0].replace("/","\")
        if "/" in self.music_file:
            self.file_name = self.music_file.rsplit("/",1)[1]
        else:
            self.file_name = self.music_file

        self.filenames = next(walk(self.file_path), (None, None, []))[2]
        self.file_count = 0

        for i in self.filenames:
            if i == self.file_name:
                break
            self.file_count += 1

        self.next_file = self.file_count + 1
        self.directory_limit = len(self.filenames)
        if self.next_file == self.directory_limit:
            self.next_file = 0
        self.music_file = self.file_path + "/" + self.filenames[self.next_file]
        self.file_count = 0
        mixer.init()
        try:
            mixer.music.load(self.music_file)
        except pygame.error as message:
            while True:
                self.next_file += 1
                if self.next_file == self.directory_limit:
                    self.next_file = 0
                self.music_file = self.file_path + "/" + self.filenames[self.next_file]
                self.file_extension = self.music_file.rsplit(".",1)[1]
                if (".wav") or (".mp3") in self.file_extension:
                    mixer.music.load(self.music_file)
                    break
        
        mixer.music.play()



    def back(self):
        self.file_path = (self.music_file.rsplit("/",1))[0].replace("/","\")
        if "/" in self.music_file:
            self.file_name = self.music_file.rsplit("/",1)[1]
        else:
            self.file_name = self.music_file

        self.filenames = next(walk(self.file_path), (None, None, []))[2]
        self.file_count = 0

        for i in self.filenames:
            if i == self.file_name:
                break
            self.file_count += 1

        self.back_file = self.file_count - 1
        self.directory_limit = len(self.filenames)
        if self.back_file == self.directory_limit:
            self.back_file = 0
        self.music_file = self.file_path + "/" + self.filenames[self.back_file]
        self.file_count = 0
        mixer.init()
        try:
            mixer.music.load(self.music_file)
        except pygame.error as message:
            while True:
                self.back_file += 1
                if self.back_file == self.directory_limit:
                    self.back_file = 0
                self.music_file = self.file_path + "/" + self.filenames[self.back_file]
                self.file_extension = self.music_file.rsplit(".",1)[1]
                if (".wav") or (".mp3") in self.file_extension:
                    mixer.music.load(self.music_file)
                    break
        
        mixer.music.play()







        ########################################################################################################      




root = tk.Tk()
MP(root)
root.mainloop()
  1. How do I make an audio scrubber that allows the users to go to different time intervals of the song?

2

Answers


  1. I’m not too sure about the audio scrubber, I’ve never needed audio for my tkinter interfaces so I couldn’t advise on that. For an image, you may find adding something like this to your __init__ method helpful:

    # import the background image
    self.background = Image.open('path/to/image')
    self.background = self.background.resize((x_dim, y_dim), Image.ANTIALIAS)
    self.background = ImageTk.PhotoImage(self.background)
    
    # create background
    win.create_image(x_pos, y_pos, image=self.background)
    

    For the imports you’ll need:

    # 'pip install pillow' if needed
    from PIL import ImageTk, Image
    

    You would of course need to define x_dim and y_dim to make your image fit properly. For x_pos and y_pos, the coordinates you provide will be Tkinter places the center-point of the background image.

    Hopefully that helps!

    Login or Signup to reply.
  2. At first congrats for getting into Python this quickly !

    For your first question :

    You can import images in tkinter using the PhotoImage class provided in tkinter :

    bg = PhotoImage(file="image_path")

    After importing the image, you can place the image onto the GUI using a label :

    backgroundLabel = Label(win, image=bg)
    backgroundLabel.place(x=0, y=0)
    

    I’ve personnaly never done a videoplayer in tkinter, but i found this pypi module.

    And I don’t know about your second question, sorry.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search