包
pynput.mouse
包含用于控制和监视鼠标的类。
使用
pynput.mouse.Controller
像这样:
from pynput.mouse import Button, Controller mouse = Controller() # Read pointer position print('The current pointer position is {0}'.format( mouse.position)) # Set pointer position mouse.position = (10, 20) print('Now we have moved it to {0}'.format( mouse.position)) # Move pointer relative to current position mouse.move(5, -5) # Press and release mouse.press(Button.left) mouse.release(Button.left) # Double click; this is different from pressing and releasing # twice on macOS mouse.click(Button.left, 2) # Scroll two steps down mouse.scroll(0, 2)
使用
pynput.mouse.Listener
像这样:
from pynput import mouse def on_move(x, y): print('Pointer moved to {0}'.format( (x, y))) def on_click(x, y, button, pressed): print('{0} at {1}'.format( 'Pressed' if pressed else 'Released', (x, y))) if not pressed: # Stop listener return False def on_scroll(x, y, dx, dy): print('Scrolled {0} at {1}'.format( 'down' if dy < 0 else 'up', (x, y))) # Collect events until released with mouse.Listener( on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener: listener.join() # ...or, in a non-blocking fashion: listener = mouse.Listener( on_move=on_move, on_click=on_click, on_scroll=on_scroll) listener.start()
鼠标监听器是
threading.Thread
,且将从线程援引所有回调。
调用
pynput.mouse.Listener.stop
从任何地方,引发
StopException
或返回
False
从回调以停止监听器。
当使用上文非阻塞版本时,当前线程将继续执行。这可能是必要的,当与纳入主循环的其它 GUI 框架集成时,但当从脚本运行时,这将导致程序立即终止。
The listener callbacks are invoked directly from an operating thread on some platforms, notably Windows .
This means that long running procedures and blocking operations should not be invoked from the callback, as this risks freezing input for all processes.
A possible workaround is to just dispatch incoming messages to a queue, and let a separate thread handle them.
If a callback handler raises an exception, the listener will be stopped. Since callbacks run in a dedicated thread, the exceptions will not automatically be reraised.
To be notified about callback errors, call
Thread.join
on the listener instance:
from pynput import mouse class MyException(Exception): pass def on_click(x, y, button, pressed): if button == mouse.Button.left: raise MyException(button) # Collect events until released with mouse.Listener( on_click=on_click) as listener: try: listener.join() except MyException as e: print('{0} was clicked'.format(e.args[0]))
一旦
pynput.mouse.Listener.stop
has been called, the listener cannot be restarted, since listeners are instances of
threading.Thread
.
If your application requires toggling listening events, you must either add an internal flag to ignore events when not required, or create a new listener when resuming listening.
To simplify scripting, synchronous event listening is supported through the utility class
pynput.mouse.Events
. This class supports reading single events in a non-blocking fashion, as well as iterating over all events.
To read a single event, use the following code:
from pynput import mouse # The event listener will be running in this block with mouse.Events() as events: # Block at most one second event = events.get(1.0) if event is None: print('You did not interact with the mouse within one second') else: print('Received event {}'.format(event))
To iterate over mouse events, use the following code:
from pynput import mouse # The event listener will be running in this block with mouse.Events() as events: for event in events: if event.button == mouse.Button.right: break else: print('Received event {}'.format(event))
Please note that the iterator method does not support non-blocking operation, so it will wait for at least one mouse event.
The events will be instances of the inner classes found in
pynput.mouse.Events
.
Recent versions of _Windows_ support running legacy applications scaled when the system scaling has been increased beyond 100%. This allows old applications to scale, albeit with a blurry look, and avoids tiny, unusable user interfaces.
This scaling is unfortunately inconsistently applied to a mouse listener and a controller: the listener will receive physical coordinates, but the controller has to work with scaled coordinates.
This can be worked around by telling Windows that your application is DPI aware. This is a process global setting, so _pynput_ cannot do it automatically. Do enable DPI awareness, run the following code:
import ctypes PROCESS_PER_MONITOR_DPI_AWARE = 2 ctypes.windll.shcore.SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE)
pynput.mouse.
Controller
[source]
¶
A controller for sending virtual mouse events to the system.
click
(
button
,
count=1
)
[source]
¶
Emits a button click event at the current position.
The default implementation sends a series of press and release events.
| 参数: |
|
|---|
move
(
dx
,
dy
)
[source]
¶
Moves the mouse pointer a number of pixels from its current position.
| 参数: |
|
|---|---|
| 引发: | ValueError – if the values are invalid, for example out of bounds |
位置
¶
The current position of the mouse pointer.
This is the tuple
(x, y)
, and setting it will move the pointer.
press
(
button
)
[source]
¶
Emits a button press event at the current position.
| 参数: | button ( Button ) – The button to press. |
|---|
release
(
button
)
[source]
¶
Emits a button release event at the current position.
| 参数: | button ( Button ) – The button to release. |
|---|
scroll
(
dx
,
dy
)
[source]
¶
发送卷动事件。
| 参数: |
|
|---|---|
| 引发: | ValueError – if the values are invalid, for example out of bounds |
pynput.mouse.
Listener
(
on_move=None
,
on_click=None
,
on_scroll=None
,
suppress=False
,
**kwargs
)
[source]
¶
用于鼠标事件的监听器。
Instances of this class can be used as context managers. This is equivalent to the following code:
listener.start() try: listener.wait() with_statements() finally: listener.stop()
此类继承自
threading.Thread
并支持其所有方法。它会设置
daemon
to
True
当创建时。
| 参数: |
|
|---|
__init__
(
on_move=None
,
on_click=None
,
on_scroll=None
,
suppress=False
,
**kwargs
)
[source]
¶
始终应采用关键词自变量调用此构造函数。自变量:
group should be None; reserved for future extension when a ThreadGroup class is implemented.
target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.
name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number.
args is the argument tuple for the target invocation. Defaults to ().
kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.
If a subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread.
running
¶
Whether the listener is currently running.
start
(
)
¶
启动线程活动。
It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control.
This method will raise a RuntimeError if called more than once on the same thread object.
stop
(
)
¶
Stops listening for events.
When this method returns, no more events will be delivered. Once this method has been called, the listener instance cannot be used any more, since a listener is a
threading.Thread
, and once stopped it cannot be restarted.
To resume listening for event, a new listener must be created.
wait
(
)
¶
Waits for this listener to become ready.