2

I am new to python and I found a code that detects mouse buttons when held down and released, but i want "x" to turn True when both of the buttons held down, how can I do this

     # This function will be called when any key of mouse is pressed
def on_click(*args):
  # see what argument is passed.
  print(args)
  if args[-1]:
    # Do something when the mouse key is pressed.
    print('The "{}" mouse key has held down'.format(args[-2].name))

elif not args[-1]:
    # Do something when the mouse key is released.
    print('The "{}" mouse key is released'.format(args[-2].name))

# Open Listener for mouse key presses
with Listener(on_click=on_click) as listener:
 # Listen to the mouse key presses
 listener.join()

1 Answers1

1

To detect if both buttons are held down simultaneously, three variables will be required (initialise these at the start of your program, outside of the on_click function):

global leftPressed, rightPressed, bothPressed
leftPressed = False
rightPressed = False
bothPressed = False

*note the variables are global here, as multiple versions of on_click will be accessing and modifying the variables

Then, in the first if statement (when a mouse button has been pressed):

if args[-2].name == "left":
    leftPressed = True
elif args[-2].name == "right":
    rightPressed = True
            
if leftPressed and rightPressed:
    # if both left and right are pressed
    bothPressed = True

And in the second if statement (when a mouse button has been released)

if args[-2].name == "left":
    leftPressed = False
elif args[-2].name == "right":
    rightPressed = False

# as one key has been released, both are no longer pressed
bothPressed = False
print(bothPressed)

Finally, to access the global variables from within the function on_click, place this line at the start of the function:

global leftPressed, rightPressed, bothPressed

See a full version of the code here:

https://pastebin.com/nv9ddqMM

John Skeen
  • 223
  • 1
  • 5
  • 9