如何检测点击了哪个按钮? (输入法)

How to detect what button was clicked? (Pynput)

我正在尝试检测单击了哪个鼠标按钮

所以这是我的代码:

from pynput.mouse import Listener

def on_click(button, pressed):
   if button.Left and pressed:
       print("You pressed the left mouse button")
   if button.Right and pressed:
       print("You pressed the right mouse button")
       

所以没有错误,但没有任何想法?

来自文档 Here

代码

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(button)  # Print button to see which button of mouse was pressed
    print('{0} at {1}'.format(
        'Pressed' if pressed else 'Released',
        (x, y)))
    



# Collect events until released
with mouse.Listener(
        on_click=on_click
       ) as listener:
    listener.join()

# ...or, in a non-blocking fashion:
listener = mouse.Listener(on_click=on_click)
listener.start()

如您所见,函数 on_click 中的 button 参数告诉您按下了哪个按钮。

EDIT:

以下是您可以根据按下的鼠标按钮处理操作的方法

 def on_click(x, y, button, pressed):
    btn = button.name

    if btn == 'left':
        print('Left if Pressed')
        # ====== < Handle Pressed or released Event ====== > # 
        if pressed:
            print('Do somethin when Pressed with LEft')
        else:
            print('LEFT is Released')
    elif btn == 'right':
        print('Right BTN was pressed ')
        # ====== < Handle Pressed or released Event ====== > # 
        if not pressed:
            print('right Button is released')
        else:
            pass

我 post 第二个答案,因为在代码 here

中发现问题的性质不同

问题是你如何调用导入。

正确代码

from pynput import mouse


mouse_ = mouse.Controller()
button = mouse.Button

def on_click(x, y, button, pressed):
    btn = button.name

    if btn == 'left':
        if pressed:
            mouse_.click(button_.left)
            print('works')


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

复制并粘贴代码而不做任何更改。

警告

当我使用 button.left 时,我的电脑变得非常迟钝,所以我建议您不要使用 is,除非您知道自己在做什么