OddlySpecific
OddlySpecific

Reputation: 59

Kivy on_press vs on_touch_down

I have a number in a Kivy label and 2 buttons, one which increments that number, one which decrements it. I was surprised to find that when using on_touch_down the + button would not work. I commented out the - button and the + button started working.

I changed the on_touch_down to on_press and both buttons exist/function harmoniously.

Can someone tell me why?

Here is an example .py file:

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


class Counter(BoxLayout):

    def count_up(self):
        value = self.ids.the_number.text
        self.ids.the_number.text = str(int(value) + 1)

    def count_down(self):
        value = self.ids.the_number.text
        self.ids.the_number.text = str(int(value) - 1)


class ProofApp(App):
    def build(self):
        return Counter()


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

and the .kv file:

<Counter>:
    AnchorLayout:
        anchor_x: 'center'
        anchor_y: 'top'

        BoxLayout:
            orientation: 'horizontal'

            BoxLayout:

                Label:
                    id: the_number
                    text: "1"

            BoxLayout:
                orientation: 'vertical'
                padding: 2

                Button:
                    id: count_up
                    text: "+"
                    on_press: root.count_up()

                Button:
                    id: count_down
                    text: "-"
                    on_press: root.count_down()

Upvotes: 1

Views: 4256

Answers (1)

BlueLeftShoe
BlueLeftShoe

Reputation: 58

on_touch_down fires everything within a widget tree. Your buttons were cancelling each other out.

If your buttons were doing something else, something that did not cancel each other out, then you would see both actions fire. Such as if one button printed "hello" and one printed "world" then pressing the button that didn't appear to be working would print "hello world".

Upvotes: 4

Related Questions