Tag – Python

Blog

  • posted by mark
  • on Oct. 28, 2015

Here’s a snippet for Kivy, which adds functionality to get the widget at a given screen position. It’s probably not the most refined approach in the world but until we can get a proper mouse over event, this seems to work for now.

To use it, simply add it to your App class like:


class TestApp(WidgetPosition, App):
...

and call get_widget_at(pos)

And here’s the code:

class WidgetPosition:
    def get_widget_at(self, pos, node=None):
        x, y = pos

        if not node:
            node = self.root

        for widget in node.children:
            if self._is_over_widget(widget, x, y):
                return self.get_widget_at(pos, widget)

        if node == self.root and not self._is_over_widget(node, x, y):
            return None

        return node

    def _is_over_widget(self, widget, x, y):
        if x >= widget.pos[0] and x <= widget.pos[0] + widget.width and \
                y >= widget.pos[1] and y <= widget.pos[1] + widget.height:
            return True
        return False

Back