Python语言26键钢琴程序代码QZQ

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.core.audio import SoundLoader
import os

class PianoGrid(GridLayout):
    def __init__(self, **kwargs):
        super(PianoGrid, self).__init__(**kwargs)
        self.cols = 26  # 26个钢琴键
        self.notes = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

        for note in self.notes:
            button = Button(
                text=note,                # 显示音符名称
                size_hint=(1, 0.15),     # 调整按钮高度
                on_press=self.play_sound
            )
            button.sound_file = f"{note}.wav"  # 声音文件命名规则
            self.add_widget(button)

    def play_sound(self, instance):
        sound_path = instance.sound_file
        sound = SoundLoader.load(sound_path)
        if sound:
            sound.play()


class PianoApp(App):
    def build(self):
        return PianoGrid()


if __name__ == '__main__':
    PianoApp().run()

你可能感兴趣的:(python,开发语言)