0

I recently start to make GUI applications and I want to make a simple music player. I'm using pygame library to play the songs and that's works fine. The problem is that the window freezes when a song is playing and I am not able to press any buttons. Can anyone point me into the right direction? I've search a lot and found nothing. Here is the code:

import tkinter.filedialog as filedialog
from tkinter import *
import os
import pygame

def play(position):
    pygame.mixer.music.load(listOfSongs[position])
    global index
    index += 1
    pygame.mixer.music.play()
    while pygame.mixer.music.get_busy():
        pygame.time.Clock().tick(5)

def next(event):
    global index
    index += 1
    play(index)


root = Tk()
listOfSongs = []
directory = filedialog.askdirectory()
print("Loading files from directory: ", directory)
os.chdir(directory)
pygame.mixer.init()
for file in os.listdir(directory):
    if file.endswith('.mp3'):
        print("Appending file: ", file)
        listOfSongs.append(file)

index = 0
play(index)
b = Button(root, text="Next", bg='red', width=5)
b.bind("<Button-1>", next)
b.pack()
root.mainloop()
Hadi Farah
  • 1,091
  • 2
  • 9
  • 27
Mareș Ștefan
  • 430
  • 1
  • 4
  • 13
  • You are playing the song using the same thread that the Tk interface is running on. When the song is playing, it is probably blocking the rest of the program. Google for using Tk with threads – James Jul 10 '18 at 11:17
  • @James this worked, thanks a lot, I didn't know about threads in python – Mareș Ștefan Jul 10 '18 at 12:08
  • 2
    Possible duplicate of [Tkinter: How to use threads to preventing main event loop from "freezing"](https://stackoverflow.com/questions/16745507/tkinter-how-to-use-threads-to-preventing-main-event-loop-from-freezing) – James Jul 10 '18 at 12:17

0 Answers0