0

I am trying to create a piano model with some actual piano notes that are available in .mp3 format and I am using tkinter library to create the GUI and playsound library to play the mp3 files, and I am also using the threading in order to play individual notes independently at the same time.

My concern about the code is, how can I get the Button ID of individual buttons so that I can call a specific function to play a specific note depending upon the ID number of the button using lambda function? (Currently I have got three individual piano notes C,E,G but I can only assign one particular note, for all the buttons which I want to change depending on the Button ID)

Cannot return exact value from noteFinder() function and pass the value to playNotes() function with the matched index number of the button and the note list. (Currently debugging returns "False" as the console output result)

Here is my code and the screenshot of my project is also attached. It would be a great help for me.

# importing necessary libraries
from tkinter import *
import playsound
import threading
import os
import time

# folder path declaration
folder_path = r'E:\\Programming\\python_practice\\music_notes'

# music note declaration
noteList = [] # empty list to store music notes as list elements

def listDir(dir): # get notes from the path and put into the list
    fileNames = os.listdir(dir)
    for fileName in fileNames:
        noteList.append(fileName)

listDir(folder_path)


# Creating the temporary tkinter windows which will later be replaced with RbPi button interface
root = Tk()
root.title("Python Piano")


files =[]

for i in range(len(noteList)):
    files.append(str(i))

btns = []

class Piano:
    
    def __init__(self,master):

        global myFrame

        myFrame = Frame(master)
        myFrame.pack()

        t = threading.Thread(target= self.playNotes)
        t.start()
        time.sleep(0.1)
                

    def buttonGenerator(self):

        for i in range(len(files)):
            btns.append(Button(myFrame, text=files[i], padx=5, pady=40, command = lambda t = btns:self.noteFinder(t)))
            btns[i].grid(column=[i], row=0)


    def noteFinder(self,note):
        if note in noteList:
            print("True")
        else:
            print("False")
        
        
    def playNotes(self):
        i = len(noteList)
        if i in btns:
            if btns[i] == noteList[i]:
                print(i)
            
        playsound.playsound(folder_path + "\\" + noteList[i])
        
    

myPiano = Piano(root)
myPiano.buttonGenerator()

root.mainloop()

Here is the screenshot of the piano gui with terminal output

0 Answers0