Getting cursor position in Python

后端 未结 11 1117
旧巷少年郎
旧巷少年郎 2020-12-02 22:29

Is it possible to get the overall cursor position in Windows using the standard Python libraries?

相关标签:
11条回答
  • 2020-12-02 23:04
    win32gui.GetCursorPos(point)
    

    This retrieves the cursor's position, in screen coordinates - point = (x,y)

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

    Retrieves information about the global cursor.

    Links:

    • http://msdn.microsoft.com/en-us/library/ms648389(VS.85).aspx
    • http://msdn.microsoft.com/en-us/library/ms648390(VS.85).aspx

    I am assuming that you would be using python win32 API bindings or pywin32.

    0 讨论(0)
  • 2020-12-02 23:05

    Using the standard ctypes library, this should yield the current on screen mouse coordinates without any third party modules:

    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)
    

    I should mention that this code was taken from an example found here So credit goes to Nullege.com for this solution.

    0 讨论(0)
  • 2020-12-02 23:07

    I found a way to do it that doesn't depend on non-standard libraries!

    Found this in Tkinter

    self.winfo_pointerxy()
    
    0 讨论(0)
  • 2020-12-02 23:09

    If you're doing automation and want to get coordinates of where to click, simplest and shortest approach would be:

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

    This will track your mouse position and would keep on printing coordinates.

    0 讨论(0)
  • 2020-12-02 23:13

    You will not find such function in standard Python libraries, while this function is Windows specific. However if you use ActiveState Python, or just install win32api module to standard Python Windows installation you can use:

    x, y = win32api.GetCursorPos()
    
    0 讨论(0)
  • 2020-12-02 23:13

    Using pyautogui

    To install

    pip install pyautogui

    and to find the location of the mouse pointer

    import pyautogui
    print(pyautogui.position())
    

    This will give the pixel location to which mouse pointer is at.

    0 讨论(0)
提交回复
热议问题