【问题标题】:How to get the text cursor position in Windows?如何在 Windows 中获取文本光标位置?
【发布时间】:2010-09-13 07:52:42
【问题描述】:

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

【问题讨论】:

  • 对于要求使用标准 Python 库完成此操作的问题,实际上没有解决方案。选择的答案需要您安装额外的模块。我之所以这么说,是因为谷歌搜索问题直接指向这里。 (您可以使用 tkinter,但它要求您有一个同时运行的 tkinter 实例(?)AFAIK)
  • 看到 99% 的编程人群似乎认为 "cursor position"鼠标/指针位置 是一回事,这令人沮丧,当与the truth 相距甚远。在此 OP 中,用户要求的是“文本”位置,而不是指针的图形 (x,y) 坐标

标签: python windows


【解决方案1】:

使用标准 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)

我应该提一下,这段代码取自 here 的一个示例 因此,这个解决方案归功于 Nullege.com。

【讨论】:

  • 呸哈哈,当我研究这个时,刚刚在 Nullege 发现了同样的 sn-p。但这应该是公认的答案,因为它不使用 3rd 方代码,而且它的作用就像一个魅力。
  • 我对此进行了修复,因为它会导致人们可能不会立即注意到的错误:光标位置是有符号的,而不是无符号的,如果鼠标位于左侧的监视器上,则可能是负数主要的。使用“c_ulong”,您最终得到的坐标是 4294967196 而不是 -100。 (它也可以垂直发生,但不太常见。)
  • 对这段代码一步一步发生的事情的评论?
【解决方案2】:
win32gui.GetCursorPos(point)

这会检索光标的位置,在屏幕坐标中 - point = (x,y)

flags, hcursor, (x,y) = win32gui.GetCursorInfo()

检索有关全局光标的信息。

链接:

我假设您将使用 python win32 API 绑定或 pywin32。

【讨论】:

  • 我猜这不适用于 Ubuntu。对吗?
【解决方案3】:

您不会在标准 Python 库中找到此类函数,而此函数是 Windows 特定的。但是,如果您使用 ActiveState Python,或者只是将 win32api 模块安装到标准 Python Windows 安装中,您可以使用:

x, y = win32api.GetCursorPos()

【讨论】:

  • 通过 pip install pypiwin32 安装这个
  • 要安装的的正确名称是pywin32(不是pypiwin32)。
【解决方案4】:

我找到了一种不依赖非标准库的方法!

在 Tkinter 中找到这个

self.winfo_pointerxy()

【讨论】:

  • NameError: name 'self' is not defined
  • 其实应该先创建一个实例。就像p=Tkinter.Tk(),最后你得到p.winfo_pointerxy(),它返回一个当前光标位置的元组:)
【解决方案5】:

使用 pyautogui

安装

pip install pyautogui

并找到鼠标指针的位置

import pyautogui
print(pyautogui.position())

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

【讨论】:

    【解决方案6】:

    对于使用本机库的 Mac:

    import Quartz as q
    q.NSEvent.mouseLocation()
    
    #x and y individually
    q.NSEvent.mouseLocation().x
    q.NSEvent.mouseLocation().y
    

    如果没有安装Quartz-wrapper:

    python3 -m pip install -U pyobjc-framework-Quartz
    

    (题主说的是windows,但是很多Mac用户都是因为标题才来这里的)

    【讨论】:

      【解决方案7】:

      这可能是您的问题的代码:

      # 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() 已经回答herehere
      【解决方案8】:

      先决条件

      安装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())
      

      【讨论】:

        【解决方案9】:

        这是可能的,甚至没有那么混乱!只需使用:

        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='')
        【解决方案10】:
        sudo add-apt-repository ppa:deadsnakes
        sudo apt-get update
        sudo apt-get install python3.5 python3.5-tk
        # or 2.7, 3.6 etc
        # sudo apt-get install python2.7 python2.7-tk
        
        # mouse_position.py
        import Tkinter
        p=Tkinter.Tk()
        print(p.winfo_pointerxy()
        

        或者从命令行使用单行:

        python -c "import Tkinter; p=Tkinter.Tk(); print(p.winfo_pointerxy())"
        (1377, 379)
        

        【讨论】:

          【解决方案11】:

          使用 pygame

          import pygame
          
          mouse_pos = pygame.mouse.get_pos()
          

          这将返回鼠标的 x 和 y 位置。

          查看此网站:https://www.pygame.org/docs/ref/mouse.html#pygame.mouse.set_pos

          【讨论】:

          • 这会返回一个元组 (-1,-1) !! (当然,在初始化 pygame 之后,这里就没有了!)这是一个强烈反对的案例,但我不喜欢也从不这样做,与许多其他人不同。我更喜欢写 cmets。更有帮助。
          【解决方案12】:

          如果您正在进行自动化并希望获得点击位置的坐标,最简单和最短的方法是:

          import pyautogui
          
          while True:
              print(pyautogui.position())
          

          这将跟踪您的鼠标位置并继续打印坐标。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-07-02
            • 2023-03-16
            • 1970-01-01
            • 1970-01-01
            • 2010-12-02
            • 2010-09-25
            • 1970-01-01
            • 2011-02-04
            相关资源
            最近更新 更多