Kivy:如何可靠地设置[键盘]焦点 - 鼠标按下

时间:2017-01-10 14:44:50

标签: python kivy

我试图在点击它时将焦点分配给它。我只是部分成功。

尝试1:

class TreeWidget(Widget, FocusBehavior):

    def __init__(self, **kwargs):
        super(TreeWidget, self).__init__(**kwargs)

    def on_touch_down(self, touch):
        ret = super(TreeWidget, self).on_touch_down(touch)

        if not self.collide_point(*touch.pos):
            return ret

        self.focus = True

        # ...

        return ret

这将鼠标按下和鼠标按下之间的短暂时间设置为小部件。

尝试2:

尝试2是在下面添加以下代码;这对任何(可见的)方式都没有帮助;即在释放鼠标后,我的小部件仍无焦点。

class ...

    def on_touch_up(self, touch):
        if self.collide_point(*touch.pos):
            self.focus = True

        ret = super(TreeWidget, self).on_touch_up(touch)
        return ret  
        return True #  (attempt 2b, also unsuccessful)

尝试3:

class TreeWidget(Widget, FocusBehavior):

    def __init__(self, **kwargs):
        super(TreeWidget, self).__init__(**kwargs)

    def on_touch_down(self, touch):
        ret = super(TreeWidget, self).on_touch_down(touch)

        if not self.collide_point(*touch.pos):
            return ret

        touch.grab(self)

        self.focus = True

        # ...

        return ret

    def on_touch_up(self, touch):
        # Taken from the docs: https://kivy.org/docs/guide/inputs.html#grabbing-touch-events
        if touch.grab_current is self:

            # ok, the current touch is dispatched for us.
            # do something interesting here
            print('Hello world!')
            self.focus = True

            # don't forget to ungrab ourself, or you might have side effects
            touch.ungrab(self)

            # and accept the last up
            return True

虽然这个解决方案有效,但我不明白为什么。这意味着我很快就会遇到相关问题。有人可以向我解释我做错了什么(或者说是对的)。特别是,导致鼠标失去焦点的原因(在所有解决方案中)以及为什么不在解决方案2中修复?

上下文:Kivy v1.9.1上的桌面应用程序,Python v3.4.3。

2 个答案:

答案 0 :(得分:0)

原来问题是超类的排序:

更改第一次尝试的第一行就像解决问题一样:

class TreeWidget(FocusBehavior, Widget):

在此讨论的帮助下:https://groups.google.com/forum/#!topic/kivy-users/MrKU4-F0wpU

答案 1 :(得分:0)

尝试将 unfocus_on_touch 小部件属性设置为 False

class Attempt1(Attempt):

def on_touch_down(self, touch):
    ret = super(Attempt1, self).on_touch_down(touch)

    if not self.collide_point(*touch.pos):
        return ret

    self.unfocus_on_touch = False
    self.focus = True
    return ret