Python 检查鼠标是否被点击

The*_*ive 5 python mouseevent keyboard-events

所以我试图用 Python 构建一个简短的脚本。我想要做的是,如果单击鼠标,鼠标将重置到某个任意位置(现在是屏幕中间)。我希望它在后台运行,因此它可以在操作系统(很可能是 Chrome 或某些网络浏览器)中运行。我也希望用户可以按住某个按钮(比如 ctrl),然后他们可以点击离开而不重置位置。这样他们就可以毫无挫折地关闭脚本。

我很确定我知道如何做到这一点,但我不确定要使用哪个库。我更喜欢它是跨平台的,或者至少是 Windows + Mac。到目前为止,这是我的代码:

#! python3
# resetMouse.py - resets mouse on click - usuful for students with
# cognitive disabilities.

import pymouse

width, height = m.screen_size()
midWidth = (width + 1) / 2
midHeight = (height + 1) / 2

m = PyMouse()
k = PyKeyboard()


def onClick():
    m.move(midWidth, midHeight)


try:
    while True:
        # if button is held down:
            # continue
        # onClick()
except KeyboardInterrupt:
    print('\nDone.')
Run Code Online (Sandbox Code Playgroud)

Mah*_*san 7

尝试这个

from pynput.mouse import Listener


def on_move(x, y):
    print(x, y)


def on_click(x, y, button, pressed):
    print(x, y, button, pressed)


def on_scroll(x, y, dx, dy):
    print(x, y, dx, dy)


with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
    listener.join()
Run Code Online (Sandbox Code Playgroud)

  • 您也能解释一下您的答案吗?只有代码不是正确的答案(来自评论) (3认同)

小智 1

我只用 win32api 就能让它工作。单击任何窗口时它都会起作用。

import win32api
import time

width = win32api.GetSystemMetrics(0)
height = win32api.GetSystemMetrics(1)
midWidth = int((width + 1) / 2)
midHeight = int((height + 1) / 2)

state_left = win32api.GetKeyState(0x01)  # Left button up = 0 or 1. Button down = -127 or -128
while True:
    a = win32api.GetKeyState(0x01)
    if a != state_left:  # Button state changed
        state_left = a
        print(a)
        if a < 0:
            print('Left Button Pressed')
        else:
            print('Left Button Released')
            win32api.SetCursorPos((midWidth, midHeight))
    time.sleep(0.001)
Run Code Online (Sandbox Code Playgroud)