繁体   English   中英

如何仅在按下键时触发鼠标单击? 在 Python

[英]How to trigger mouse clicks only when a key is pressed ? In Python

我想制作一个程序,或者当我单击一个键时,如果我不单击它会停止的键,鼠标会自动单击(只要我单击该键)。

我不希望只有当我触摸一次按键时才会发生点击,但只要按住按键(也可以是按下鼠标的左键触发像 razer 突触鼠标一样的点击)

任何想法?

编辑1:

这个可以工作,但在按住某个键时不起作用(即使按住单击它也不起作用)它只检测到鼠标单击一次,然后它自己单击而不是在按住键时单击下...

import pyautogui, time
from pynput import mouse
from pynput.mouse import Button,Controller
from tkinter import *
from tkinter import ttk


root = Tk()
root.geometry('500x400') 

combo = ttk.Combobox(root,values=['ctrl','shift','alt'],width=5)
combo.set('Key...')
combo.pack()



def on_click(x, y, button, pressed):
    if button == mouse.Button.left:
        while pressed:
            pyautogui.click()
            pyautogui.PAUSE = 0.1
        else:
            return False

with mouse.Listener(
    on_click=on_click
    ) as Listener:
         Listener.join()

root.mainloop()

您可以使用鼠标模块( pip install mouse )来设置鼠标钩子(热键),让您触发全局点击。 但是,为了管理此单击的开始和结束,您需要使用新线程(如果您想了解更多信息,这里是线程的简短介绍)。 当您按下热键时,您会想要开始一个线程。 该线程将继续单击,直到您触发停止它的事件。 您将通过释放热键来触发此事件。 因此,线程(以及随之而来的点击)将在您按下热键时开始,并在您让它备份时结束。

这是一段使用鼠标中键(滚动)作为热键的代码:

import mouse  # pip install mouse
import threading
import pyautogui

pyautogui.PAUSE = 0.1  # set the automatic delay between clicks, default is 0.1
    
def repeat_function(kill_event):
    # as long as we don't receive singal to end, keep clicking
    while not kill_event.is_set():
        pyautogui.click()

while True:
    # create the event that will kill our thread, don't trigget it yet
    kill_event = threading.Event()
    # create the thread that will execute our clicking function, don't start it yet
    new_thread = threading.Thread(target=lambda: repeat_function(kill_event))

    # set a hook that will start the thread when we press middle mouse button
    mouse.on_button(new_thread.start, (), mouse.MIDDLE, mouse.DOWN)
    # set a hook that will kill the thread when we release middle button
    mouse.on_button(kill_event.set, (), mouse.MIDDLE, mouse.UP)

    # wait for user to use the hotkey
    mouse.wait(mouse.MIDDLE, mouse.UP)
    # remove hooks that used the killed thread and start again with a new one
    mouse.unhook_all()

如果您想使用鼠标右键,请将mouse.MIDDLE替换为mouse.RIGHT 我不建议使用鼠标左键作为热键,因为 pyautogui 会模拟单击此按钮并可能会破坏程序。 如果您想使用键盘上的某个键作为热键,请查看键盘模块。 那里的概念完全相同。

请注意,随着此代码的实现,它在等待热键并处理它时将无法执行任何其他操作。 如果您想按原样使用它,则需要将其用作单独的 python 程序。 您还可以实现此代码以在另一个程序期间在单独的线程中运行,但将其作为独立脚本启动肯定会更容易。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM