0

I am trying to detect a long press event and cancel it if the button is released before the timer times out, however the timer never gets cancelled and fires if it is a short press or a long one:

from threading import Thread

but_down = Timer(1.5,long_press)

if(but=='down'):
    but_down.start()

else:
    but_down.cancel()

def long_press():
    print('long press')

1 Answer 1

2

Your code didn't run for me due to errors, but once I fixed those it worked fine:

This outputs long press after 1.5 seconds:

from threading import Timer
but = "down"
def long_press():
    print('long press')
but_down = Timer(1.5,long_press)
if(but=='down'):
    but_down.start()
else:
    but_down.cancel()

This outputs nothing:

from threading import Timer
but = "up"
def long_press():
    print('long press')
but_down = Timer(1.5,long_press)
if(but=='down'):
    but_down.start()
else:
    but_down.cancel()

I don't know what but is but my guess is that your but=='down' test might be the cause of the error.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, my code was pseudo code as if I included the actual it would not have made much sense. It turns out that it was related to scope in the end, thanks so much for helping.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.