Kivy - MotionEvent: on_mouse_pos

Mar*_*tin 2 python mouse events kivy

kivy 是否支持在 mouse_pos 更改时触发的 MouseEvent 无需按下鼠标按钮?

我在文档中发现:

def on_motion(self, etype, motionevent):
    # will receive all motion events.
    pass

Window.bind(on_motion=on_motion)
Run Code Online (Sandbox Code Playgroud)

您还可以通过观察 mouse_pos 来监听鼠标位置的变化。

但是我无法实现它。我设法绑定它并添加到 on_motion 函数 'print('Hello world')' 但它仅由按下类型事件触发。

提前致谢

iko*_*lim 5

解决方案

绑定mouse_pos到回调。详情请参考示例。

Window.bind(mouse_pos=self.mouse_pos)
Run Code Online (Sandbox Code Playgroud)

例子

主文件

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.core.window import Window


class MousePosDemo(BoxLayout):

    def __init__(self, **kwargs):
        super(MousePosDemo, self).__init__(**kwargs)
        self.label = Label()
        self.add_widget(self.label)
        Window.bind(mouse_pos=self.mouse_pos)

    def mouse_pos(self, window, pos):
        self.label.text = str(pos)


class TestApp(App):
    title = "Kivy Mouse Pos Demo"

    def build(self):
        return MousePosDemo()


if __name__ == "__main__":
    TestApp().run()
Run Code Online (Sandbox Code Playgroud)

输出

图像01