所以我试图在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.')
答案 0 :(得分:1)
尝试一下
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()
答案 1 :(得分:0)
我能够使用pyHook和win32api使其适用于Windows:
import win32api, pyHook, pythoncom
width = win32api.GetSystemMetrics(0)
height = win32api.GetSystemMetrics(1)
midWidth = (width + 1) / 2
midHeight = (height + 1) / 2
def moveCursor(x, y):
print('Moving mouse')
win32api.SetCursorPos((x, y))
def onclick(event):
print(event.Position)
moveCursor(int(midWidth), int(midHeight))
return True
try:
hm = pyHook.HookManager()
hm.SubscribeMouseAllButtonsUp(onclick)
hm.HookMouse()
pythoncom.PumpMessages()
except KeyboardInterrupt:
hm.UnhookMouse()
print('\nDone.')
exit()
答案 2 :(得分:0)
我能够让它与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 down = 0 or 1. Button up = -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)
答案 3 :(得分:0)
以下代码非常适合我。感谢Hasan的回答。
from pynput.mouse import Listener
def is_clicked(x, y, button, pressed):
if pressed:
print('Clicked ! ') #in your case, you can move it to some other pos
with Listener(on_click=is_clicked) as listener:
listener.join()