Yakuzhy
Yakuzhy

Reputation: 235

Kivy button and game score

I am new to programming and decided to create a game in Kivy. I am stuck with quite simple problem. If there is a button and a label which shows the score, how can I use the on_press event to increment the score?

e.g. when the button is pressed, then the score changes to 1 and so on.

Also, is it better to write everything in Python file or should I use kv file too?

Upvotes: 0

Views: 1031

Answers (1)

el3ien
el3ien

Reputation: 5405

You can use python only, or kv language. That is entirely up to you. In this case we make the buttons call function, increment the label text. I will make two examples. One with python only, and one in conjunction with kivy language.

This is an example in python only:

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout

class Game(BoxLayout):

    def __init__(self,**kwargs):
        super(Game,self).__init__(**kwargs)

        self.count = 0

        self.orientation = "vertical"

        self.button = Button(on_press=self.increment, text="Increment")

        self.label = Label(text="0")

        self.add_widget(self.button)
        self.add_widget(self.label)


    def increment(self,*args):
        self.count += 1
        self.label.text = str(self.count)


class MyApp(App):
    def build(self):
        return Game()

And same app using python and kivy language.

Python file:

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty

class Game(BoxLayout):

    label_text = StringProperty()
    def __init__(self,**kwargs):
        super(Game,self).__init__(**kwargs)
        self.count = 0
        self.label_text = str(self.count)

    def increment(self,*args):
        self.count += 1
        self.label_text = str(self.count)
        print self.label_text

class MyApp(App):
    def build(self):
        return Game()


MyApp().run()

And my.kv file:

#:kivy 1.9.1

<Game>:
    orientation: "vertical"

    Button:
        text: "Increment"
        on_press: root.increment()

    Label:
        text: root.label_text

Upvotes: 2

Related Questions