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

如何在Python中不依赖PyAutoGUI获取全局鼠标坐标(支持Windows 11/10与Wayland/Fedora)

Get Mouse Cursor Position in Python (No PyAutoGUI)

Got it, let's figure out how to get the mouse cursor position in Python without relying on PyAutoGUI and its heavy dependencies like Pillow. Below are tailored solutions for your target platforms—using Python's built-in ctypes for Windows (zero extra installs) and a lightweight library approach for Wayland-based Fedora:

Windows 10/11 (Using ctypes)

Since ctypes comes pre-installed with Python, this is the most lightweight option for Windows. We'll directly call the Windows API's GetCursorPos function from user32.dll to fetch the cursor coordinates.

Here's the complete code:

import ctypes
import time

# Define a structure to hold the cursor coordinates
class POINT(ctypes.Structure):
    _fields_ = [("x", ctypes.c_long), ("y", ctypes.c_long)]

def get_mouse_position():
    pt = POINT()
    # Call Windows API to get current cursor position
    ctypes.windll.user32.GetCursorPos(ctypes.byref(pt))
    return (pt.x, pt.y)

try:
    print("Monitoring mouse position. Press Ctrl+C to stop.")
    while True:
        x, y = get_mouse_position()
        print(f"X={x}, Y={y}")
        time.sleep(2)
except KeyboardInterrupt:
    print("\nStopped monitoring mouse position.")

This code works exactly like your original PyAutoGUI version but uses no external libraries—perfect for your Windows needs.

Fedora (Wayland)

Wayland has strict security restrictions that prevent direct access to global cursor coordinates (unlike X11). The most reliable lightweight approach is to use the evdev library, which reads raw input events from the mouse device. It's a small, focused library with minimal dependencies.

Step 1: Install evdev

You can install it via pip or use Fedora's system package for better compatibility:

# Option 1: Pip install
pip install evdev

# Option 2: Fedora system package (recommended)
sudo dnf install python3-evdev

Step 2: Python Code

This code tracks the cursor position by reading relative mouse movements (since Wayland doesn't expose absolute global positions):

from evdev import InputDevice, ecodes
import time

def find_mouse_device():
    # Scan all input devices to find the mouse
    devices = [InputDevice(path) for path in InputDevice.list_devices()]
    for dev in devices:
        # Check if the device supports relative X/Y movement (a mouse trait)
        capabilities = dev.capabilities()
        if ecodes.EV_REL in capabilities:
            rel_axes = capabilities[ecodes.EV_REL]
            if ecodes.REL_X in rel_axes and ecodes.REL_Y in rel_axes:
                return dev
    raise Exception("Could not find a mouse device")

# Initialize mouse tracking (start position is relative to launch time)
mouse_device = find_mouse_device()
current_x, current_y = 0, 0
# Track last print time to avoid spamming output
last_print_time = time.time()

try:
    print("Monitoring mouse position (relative to program start). Press Ctrl+C to stop.")
    for event in mouse_device.read_loop():
        if event.type == ecodes.EV_REL:
            # Update position based on relative movement
            if event.code == ecodes.REL_X:
                current_x += event.value
            elif event.code == ecodes.REL_Y:
                current_y += event.value
            
            # Print position every 2 seconds
            current_time = time.time()
            if current_time - last_print_time >= 2:
                print(f"X={current_x}, Y={current_y}")
                last_print_time = current_time
except KeyboardInterrupt:
    print("\nStopped monitoring mouse position.")
finally:
    mouse_device.close()

Note on Wayland Limitations

If you absolutely want to avoid third-party libraries, accessing cursor position on Wayland requires low-level DBus communication with the compositor (like GNOME Shell), which is extremely complex and not practical for most use cases. The evdev approach is the best balance of simplicity and light weight here.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 06:34:21