You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Kivy中实现鼠标移动时实时打印指针位置?

当然可行!这事儿比你想的简单多了,核心就是监听Widget的鼠标移动事件就行——绝大多数GUI框架都自带这个事件接口,我给你举几个常见框架的实现例子:

具体实现示例

Qt/C++ 版本

在你的Widget子类里重写mouseMoveEvent方法,同时记得开启鼠标追踪(默认可能只有按住鼠标才触发移动事件):

#include <QWidget>
#include <QMouseEvent>
#include <QDebug>

class YourWidget : public QWidget
{
    Q_OBJECT
public:
    YourWidget(QWidget *parent = nullptr) : QWidget(parent) {
        // 开启鼠标追踪,让未按下鼠标时也能触发移动事件
        setMouseTracking(true);
    }

protected:
    void mouseMoveEvent(QMouseEvent *event) override {
        // 打印相对Widget的坐标和屏幕全局坐标
        qDebug() << "鼠标相对Widget位置:" << event->pos();
        qDebug() << "鼠标屏幕全局位置:" << event->globalPos();
        // 不要忘记调用父类方法,保证原有逻辑正常运行
        QWidget::mouseMoveEvent(event);
    }
};

PyQt/PySide 版本

Python版本逻辑完全一致,代码更简洁:

from PyQt5.QtWidgets import QWidget
from PyQt5.QtGui import QMouseEvent

class YourWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setMouseTracking(True)  # 开启鼠标追踪

    def mouseMoveEvent(self, event: QMouseEvent):
        print(f"鼠标相对Widget位置:{event.pos()}")
        print(f"鼠标屏幕全局位置:{event.globalPos()}")
        super().mouseMoveEvent(event)

Tkinter 版本

如果用Python的Tkinter,直接绑定<Motion>事件就行,不需要额外开启追踪:

import tkinter as tk

root = tk.Tk()
root.geometry("400x300")

def track_mouse(event):
    print(f"鼠标当前位置(相对窗口):x={event.x}, y={event.y}")
    print(f"鼠标当前位置(屏幕):x={event.x_root}, y={event.y_root}")

# 绑定鼠标移动事件到窗口
root.bind('<Motion>', track_mouse)

root.mainloop()
关键注意点
  • 很多框架默认只有鼠标按下时才触发移动事件,所以一定要记得开启「鼠标追踪」(比如Qt的setMouseTracking),这样鼠标悬停移动时也能持续触发事件。
  • 事件参数里一般会提供两种坐标:相对当前Widget的局部坐标,和屏幕全局坐标,根据你的需求选就行。

这样就能实现鼠标在Widget上每移动一下就打印位置啦~

内容的提问来源于stack exchange,提问作者suroh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:05:22