First, you will need to import the class Window to your code:from kivy.core.window import Window
Thus, you can get the keyboard events from the method https://kivy.org/docs/api-kivy.core.window.html#kivy.core.window.WindowBase.request_keyboard . The first parameter of the method is a function callback which will be executed when the keyboard is closed; the second parameter will be the object that will be associated with the keyboard. So I believe you can do within your class:class Piano(App):
def build(self):
self.keyboard = Window.request_keyboard(self.keyboard_closed, self)
self.keyboard.bind(on_key_down=self.on_key_down)
c = Button(text='C',font_size=30,on_release=self.do)
d = Button(text='D', font_size=30, on_release=self.re)
e = Button(text='E', font_size=30, on_release=self.mi)
f = Button(text='F', font_size=30, on_release=self.fa)
g = Button(text='G', font_size=30, on_release=self.sol)
a = Button(text='A', font_size=30, on_release=self.la)
b = Button(text='B', font_size=30, on_release=self.si)
box = BoxLayout()
box.add_widget(c)
box.add_widget(d)
box.add_widget(e)
box.add_widget(f)
box.add_widget(g)
box.add_widget(a)
box.add_widget(b)
return box`
def keyboard_closed(self):
pass
The return of the method will be an instance of https://kivy.org/docs/api-kivy.core.window.html#kivy.core.window.Keyboard , so you can do bind with the event on_key_down for your method:class Piano(App):
def build(self):
self.keyboard = Window.request_keyboard(self.keyboard_closed, self)
c = Button(text='C',font_size=30,on_release=self.do)
d = Button(text='D', font_size=30, on_release=self.re)
e = Button(text='E', font_size=30, on_release=self.mi)
f = Button(text='F', font_size=30, on_release=self.fa)
g = Button(text='G', font_size=30, on_release=self.sol)
a = Button(text='A', font_size=30, on_release=self.la)
b = Button(text='B', font_size=30, on_release=self.si)
box = BoxLayout()
box.add_widget(c)
box.add_widget(d)
box.add_widget(e)
box.add_widget(f)
box.add_widget(g)
box.add_widget(a)
box.add_widget(b)
return box`
def keyboard_closed(self):
pass
def on_key_down(self, keyboard, keycode, text, modifiers):
teclas = {
"c": self.do,
"d": self.re,
"e": self.mi,
"f": self.fa,
"g": self.sol,
"a": self.la,
"b": self.si,
}
if keycode[1] in teclas:
teclas[ keycode[1] ]()
Thus, when a key is pressed, the method on_key_down will run, checking if the key is one of the ones provided by the application and, if it is, performs the method that plays the audio.Reference https://stackoverflow.com/questions/17280341/how-do-you-check-for-keyboard-events-with-kivy