2

New to this. Trying to create a tkinter GUI where the mp3 filepath is entered, the Play button is pressed to start playing and the Stop Button is pressed to stop. With the code below, the mp3 plays fine. However the Stop button is completely unresponsive and the mp3 keeps playing. Any helpful suggestions much will be much appreciated.

import tkinter as tk
from pygame import mixer,time

class PlayMusic:
    def __init__(self):
        self.win=tk.Tk()
        self.win.geometry('500x100+600+400')
        self.win.title("Teo's Music Player")

        myfont=('Arial',14,'bold')
        self.lbl=tk.Label(self.win,text='Enter path',font=myfont)
        self.lbl.grid(row=0,column=0)
        self.ent=tk.Entry(self.win,width=25)
        self.ent.grid(row=0,column=1)

        self.b_start=tk.Button(self.win,text='Start >',command=self.start)
        self.b_start.grid(row=1,column=0)
        self.b_stop=tk.Button(self.win,text='Stop |',command=self.stop)
        self.b_stop.grid(row=1,column=1)

        self.win.mainloop()

    def start(self):
        path = str(self.ent.get())
        mixer.init()
        mixer.music.set_volume(0.2)
        mixer.music.load(path)
        mixer.music.play()
        while mixer.music.get_busy():
            time.Clock().tick(1)

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


PlayMusic()

1 Answers1

0

Just remove the while loop from the stop method:

def start(self):
    path = str(self.ent.get())
    mixer.init()
    mixer.music.set_volume(0.2)
    mixer.music.load(path)
    mixer.music.play()
    
    # DELETE
    # while mixer.music.get_busy():
    #     time.Clock().tick(1)

This loop does not terminate while the music is playing and prevents the application from responding.
You only need such a loop in a native Pygame application to prevent the application from exiting immediately (see How can I play an mp3 with pygame? and how to play wav file in python?).

Rabbid76
  • 202,892
  • 27
  • 131
  • 174