Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kivy: How to separate background touch from a widget touch?

Tags:

python

kivy

In my app, I want to handle background touches and widget touches separately. The Widget documentation ignores how to prevent bubbling from .kv events. Here's a little test case:

from kivy.app import App

class TestApp(App):

  def on_background_touch(self):
    print("Background Touched")
    return True

  def on_button_touch(self):
    print("Button Touched")

if __name__ == "__main__":
  TestApp().run()

And the .kv:

#:kivy 1.8.0

BoxLayout:
  orientation: "vertical"
  on_touch_down: app.on_background_touch()
  padding: 50, 50

  Button:
    text: "Touch me!"
    on_touch_down: app.on_button_touch()

The result: touching either the background or button triggers both handlers. Should I perform collision detection, or is there another way?

like image 931
MadeOfAir Avatar asked Dec 08 '25 06:12

MadeOfAir


1 Answers

You should perform collision detection. For instance, in a class definition:

class YourWidget(SomeWidget):
    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            do_stuff()

Edit: Actually, your method won't work anyway because the Button overlaps the BoxLayout. I would probably instead create a BoxLayout subclass and override on_touch_down, calling super first then if it returns False (indicating the touch hasn't been used yet) doing the BoxLayout interaction.

like image 98
inclement Avatar answered Dec 14 '25 11:12

inclement