Search code examples
pythonkivytouch

Why is the function triggered on the entire layout and not only on the image?


I want the function on_touch_down() in the class myField() to be called only by clicking on the image, but not on the whole screen. What do I have to change to achieve this?

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.image import Image


class MyField(Image):

    def __init__(self, **kwargs):
        super(MyField, self).__init__(**kwargs)
        self.source = "image1.jpg"
        self.size_hint = 0.1,0.1

    def on_touch_down(self, touch):
        print("touch down")


class MyLayout(FloatLayout):

    def __init__(self, **kwargs):
        super(MyLayout, self).__init__(**kwargs)
        self.add_widget(MyField())


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


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

Solution

  • The on_touch_down method belongs to Kivy's Widget and you shouldn't prevent its execution.
    What you could do though, is to modify your own version of it, to suit your needs, like that:

        def on_touch_down(self, touch):
            if self.collide_point(*touch.pos):
                print("touch down")
    

    With this, you only print something if the click is inside the boundaries of your image.