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

如何在Python的Turtle窗口中获取鼠标移动时的位置(无需点击)?

Turtle窗口移动后鼠标相对位置计算方案

直接利用Turtle底层依赖的Tkinter组件,就能绕过Turtle本身缺少窗口位置API的限制,实现准确的鼠标相对位置计算:

import turtle

# 初始化Turtle窗口
screen = turtle.Screen()
# 获取Tkinter根窗口对象(Turtle的底层实现)
root_window = screen._root

def get_window_desktop_pos():
    # 返回窗口左上角在桌面的坐标(x, y)
    return (root_window.winfo_x(), root_window.winfo_y())

def get_mouse_relative_to_canvas(desktop_x, desktop_y):
    win_x, win_y = get_window_desktop_pos()
    # 适配Turtle窗口内Canvas的默认偏移(不同系统可能有微小差异,可自行调整)
    canvas_border_x = 4
    canvas_titlebar_y = 28
    # 计算相对于Canvas的坐标
    canvas_x = desktop_x - win_x - canvas_border_x
    canvas_y = desktop_y - win_y - canvas_titlebar_y
    print(f"鼠标在Canvas上的相对位置: ({canvas_x}, {canvas_y})")

# 绑定鼠标点击事件测试
screen.onclick(get_mouse_relative_to_canvas)

turtle.done()

关键说明

  • screen._root直接调用Turtle封装的Tkinter根窗口,通过Tkinter原生的winfo_x()/winfo_y()获取窗口实时位置,窗口移动后会自动更新。
  • Canvas在Turtle窗口内存在默认偏移(边框、标题栏),如果测试时位置不准,微调canvas_border_x和canvas_titlebar_y即可适配你的系统。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:58:18