0

I am unable to figure out how to make a button appear and also make it do the right thing. O have been trying all sorts of ways to make a button for every entry in my list playlist and make it play the sound when pressed. Right now it prints a button for every line, which is good, but it doesn't make the right sound play. Every button that is added plays the sound that the last button placed should make.

import pygame
from pygame.mixer import stop
import tkinter as tk

root = tk.Tk()
root.title("Ricky's Epic Sound Collection")
root.geometry("720x550")

def playmusic(filename):
    pygame.init()
    pygame.mixer.init()
    pygame.mixer.music.load(filename)
    pygame.mixer.music.play(0)

freek = tk.Text(root, height=5, width=20)
freek.pack()

filepathfiller= tk.Button(root, text="voeg geluid toe aan library", command=lambda: zandkasteel())
filepathfiller.pack()

printButton = tk.Button(root, text="maak knoppen aan", command=lambda: button_placer())
printButton.pack()

def zandkasteel(): #creates a textfile with filepaths to the sounds
    input_a = freek.get(1.0, "end-1c")
    print(f'{input_a=}')
    with open ("sounds.txt", "a") as sound:
        sound.write(input_a)
        sound.write("\n")



def button_placer(): #creates buttons for every item in the list created by reading Sounds.txt
    fragmenten = open("sounds.txt", "r")
    playlist = fragmenten.readlines()
    print(playlist)
    for item in playlist:
        button = tk.Button(root,text=item,command=lambda:playmusic(item.strip('\n')))
        button.pack()

root.mainloop()

If anyone knows of a solution, please do share.

Skoelio
  • 13
  • 2

1 Answers1

0

I remember having had a similar issue when dynamically creating buttons. I think it might come from item.strip('\n') not being executed at the time of declaring the button. This would mean, that the anonymous function will only hold a soft copy of item, which will finally take the value of the last entry in playlist. If I understand correctly, item.strip('\n') will create a string, right? Try saving that string to a variable in the for loop and then passing that variable to playmusic in the lambda function declaration:

for item in playlist:
    song = item.strip('\n')
    button = tk.Button(root, text=item, command=lambda: playmusic(song))
    button.pack()
Alex V.
  • 180
  • 2
  • 12