如何在Windows中获取文本光标位置?

49

是否可以使用标准的Python库在Windows中获取整体鼠标位置?


2
对于一个要求使用标准Python库完成的问题,实际上并没有解决方案。所选的答案需要安装额外的模块。我之所以这么说是因为在谷歌搜索这个问题时直接指向了这里。(你可以使用tkinter,但据我所知它需要同时运行一个tkinter的实例) - Micrified
3
看到99%的编程人员似乎认为“光标位置”鼠标/指针位置是同一回事,这让人感到沮丧,因为实际上两者大相径庭。在这个帖子中,用户正在寻找“文本”位置,而不是指针的图形*(x,y)坐标*。 - not2qubit
没错!这真的很令人沮丧。但不是因为人们假设你说了什么,而主要是因为他们甚至没有看到或理解问题要求文本光标位置!!!而且发帖者甚至不在意这一点。他很可能已经忘记了自己提出的问题! - Apostolos
13个回答

61

使用标准的ctypes库,这应该可以获取当前屏幕上鼠标坐标,无需任何第三方模块

使用标准的ctypes库,这应该可以获取当前屏幕上鼠标坐标,无需任何第三方模块

from ctypes import windll, Structure, c_long, byref


class POINT(Structure):
    _fields_ = [("x", c_long), ("y", c_long)]



def queryMousePosition():
    pt = POINT()
    windll.user32.GetCursorPos(byref(pt))
    return { "x": pt.x, "y": pt.y}


pos = queryMousePosition()
print(pos)

我应该提到这段代码是从一个例子中获得的,可以在这里找到。 因此,这个解决方案归功于Nullege.com。


2
哈哈,当我在研究这个问题时,发现了同样的片段在 Nullege 上。但这应该成为被接受的答案,因为它不使用第三方代码,并且非常好用。 - RattleyCooper
4
我对此进行了修复,因为它会导致一个人可能无法立即注意到的错误:光标位置是有符号的,而不是无符号的,如果鼠标位于主显示器左侧的监视器上,则可能为负数。使用"c_ulong"时,你最终会得到类似于4294967196而不是-100的坐标。(垂直方向也可能发生,但较少见。) - Glenn Maynard
这段代码逐步发生的注释是什么? - Siemkowski

34

我猜这对Ubuntu不起作用。是这样吗? - Nathan majicvr.com

15

在标准的Python库中,您将找不到这样的函数,这个函数是专门针对Windows开发的。但是,如果您使用ActiveState Python,或者只需将win32api模块安装到标准的Python Windows安装上,您就可以使用:

x, y = win32api.GetCursorPos()

3
使用pip安装pypiwin32: pip install pypiwin32 - Atnas
要安装的软件包名称是pywin32(不是pypiwin32)。 - Christoph Rackwitz
两者都可以使用,pypiwin32也很好。 - Sam Krygsheld
你们都瞎了吗?这个问题问的是文本光标位置!! - Apostolos

8

使用pyautogui

安装

pip install pyautogui

查找鼠标指针位置的方法

import pyautogui
print(pyautogui.position())

这将给出鼠标指针所在的像素位置。


7

这是可以做到的,而且并不会太混乱!只需使用:

from ctypes import windll, wintypes, byref

def get_cursor_pos():
    cursor = wintypes.POINT()
    windll.user32.GetCursorPos(byref(cursor))
    return (cursor.x, cursor.y)

使用pyautogui的答案让我好奇这个模块是如何实现的,所以我查看了一下,下面是实现方式。

这并不像你想的那样给出光标位置。它给出了鼠标指针屏幕(x,y)坐标。请使用以下代码进行检查:while(1): print('{}\t\t\r'.format(get_cursor_pos()), end='') - not2qubit

7
我找到了一种方法来做这件事,它不依赖于非标准库!我在Tkinter中发现了这个方法。
self.winfo_pointerxy()

1
NameError: 名称 'self' 未定义 - Adam
3
实际上,首先应该创建一个实例。像这样:p=Tkinter.Tk(),最后得到 p.winfo_pointerxy(),它将返回当前光标位置的元组 :) - Waffle's Crazy Peanut

6

对于使用本地库的Mac:

import Quartz as q
q.NSEvent.mouseLocation()

#x and y individually
q.NSEvent.mouseLocation().x
q.NSEvent.mouseLocation().y

如果Quartz包装器没有安装:
python3 -m pip install -U pyobjc-framework-Quartz

这个问题指定了Windows,但很多Mac用户因为标题而来到这里。


4
这可能是您问题的一种可能代码:
# Note you  need to install PyAutoGUI for it to work


import pyautogui
w = pyautogui.position()
x_mouse = w.x
y_mouse = w.y
print(x_mouse, y_mouse)

使用 pyautogui.position() 的问题已经在这里链接1链接2中得到了解答。 - Gino Mempin

3

前提条件

安装 Tkinter。我已经包含了 win32api 作为仅适用于 Windows 的解决方案。

脚本

#!/usr/bin/env python

"""Get the current mouse position."""

import logging
import sys

logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
                    level=logging.DEBUG,
                    stream=sys.stdout)


def get_mouse_position():
    """
    Get the current position of the mouse.

    Returns
    -------
    dict :
        With keys 'x' and 'y'
    """
    mouse_position = None
    import sys
    if sys.platform in ['linux', 'linux2']:
        pass
    elif sys.platform == 'Windows':
        try:
            import win32api
        except ImportError:
            logging.info("win32api not installed")
            win32api = None
        if win32api is not None:
            x, y = win32api.GetCursorPos()
            mouse_position = {'x': x, 'y': y}
    elif sys.platform == 'Mac':
        pass
    else:
        try:
            import Tkinter  # Tkinter could be supported by all systems
        except ImportError:
            logging.info("Tkinter not installed")
            Tkinter = None
        if Tkinter is not None:
            p = Tkinter.Tk()
            x, y = p.winfo_pointerxy()
            mouse_position = {'x': x, 'y': y}
        print("sys.platform={platform} is unknown. Please report."
              .format(platform=sys.platform))
        print(sys.version)
    return mouse_position

print(get_mouse_position())

2

我知道这是一个旧线程,但一直在努力弄清如何仅使用Python标准库完成此操作。

我认为下面的代码可以用于获取Windows终端中的光标位置:

import sys
import msvcrt

print('ABCDEF',end='')
sys.stdout.write("\x1b[6n")
sys.stdout.flush()
buffer = bytes()
while msvcrt.kbhit():
    buffer += msvcrt.getch()
hex_loc = buffer.decode()
hex_loc = hex_loc.replace('\x1b[','').replace('R','')
token = hex_loc.split(';')
print(f'  Row: {token[0]}  Col: {token[1]}')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接