Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom widget not receiving touch events in kivy

Tags:

python

kivy

I am having trouble understanding kivy. I am creating a GUI with 2 buttons and a custom widget that is supposed to print the coordinates of the touch it receives, the problem is that the custom widget is not apparently receiving the touch events originating on btn2. I believe it should receive the event because the root widget (the window) must dispatch the event to all of its children (including the custom widget).

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ListProperty

class RootWidget(BoxLayout):

    def __init__(self, **kwargs):
        super(RootWidget, self).__init__(**kwargs)
        self.add_widget(Button(text="btn1"))

        self.add_widget(CustomBtn())

        self.add_widget(Button(text="btn2"))

class CustomBtn(Widget):

    pressed = ListProperty([0,0])

    def on_touch_down(self, touch):
        self.pressed = touch.pos
        return False

    def on_pressed(self, instance, value):
        print "[CustomBtn] touch down at ", value

class Demo(App):

    def build(self):
        return RootWidget()


if __name__ == '__main__':
    Demo().run()
like image 403
Apoorv Avatar asked Dec 07 '25 23:12

Apoorv


1 Answers

I found the answer, it is because the events are dispatched to the widgets in the opposite order of their addition (so in my case it would be btn2, CustomBtn and then btn1). Therefore when btn2 is clicked, it eats up the touch event, therefore CustomBtn does not receive it. Changing the order of the widgets fixes the issue.

like image 66
Apoorv Avatar answered Dec 09 '25 13:12

Apoorv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!