Markus
Markus

Reputation: 341

How do I add functionality to a button in Kivy

I am trying to add functionality to my buttons in Kivy but it is not working.

Here Is the code for the python file:

import kivy
kivy.require("1.9.1")
from kivy.uix.boxlayout import BoxLayout
from kivy.app           import App
from kivy.uix.label     import Label
from kivy.uix.button    import Button
class MainMenuApp(App):
    def build(self):
        return BoxLayout()
    def Play(self):
        print("Play Button Pressed")  
    def LeaderBoards(self):
        print("Leader Board Button Pressed")   
    def Credits(self):
        print("Credits Button Pressed")
    def Settings(self):
        print("Settings Button Pressed")
if __name__ == "__main__":
    MainMenuApp().run()

And for the kv file:

<BoxLayout>:
    orientation: "vertical"
    spacing: 20
    padding: 60, 40

    Label:
        font_name: "TitleFont.ttf"
        font_size: "60sp"
        text: "Game Title"
        size_hint: 1, 2
    Button:
        background_down: "Blue.jpg"
        background_normal: "Red.jpg"
        font_name: "TitleFont.ttf"
        font_size: "30sp"
        text: "Play"
    Button:
        background_down: "Blue.jpg"
        background_normal: "Red.jpg"
        font_name: "TitleFont.ttf"
        font_size: "30sp"
        text: "LeaderBoards"
    Button:
        background_down: "Blue.jpg"
        background_normal: "Red.jpg"
        font_name: "TitleFont.ttf"
        font_size: "30sp"
        text: "Credits"
    Button:
        background_down: "Blue.jpg"
        background_normal: "Red.jpg"
        font_name: "TitleFont.ttf"
        font_size: "30sp"
        text: "Settings"

This code makes a screen like this: Image

I know I need to use the on_click or the on_release method but I don't know how to connect it to a function in my Python file. my question is different than the other ones on this site because it uses the kv language along with Python instead of just Python

Upvotes: 1

Views: 318

Answers (1)

el3ien
el3ien

Reputation: 5405

Create a custom class, then access the class' attributtes by root.attribute

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder


Builder.load_string('''

<MyLayout>:
    Button:
        text: 'Try me!'
        on_release: root.button_pressed()

''')


class MyLayout(BoxLayout):

    def button_pressed(self):
        print("Button pressed")


class MyApp(App):

    def build(self):
        return MyLayout()


MyApp().run()

Upvotes: 2

Related Questions