Skip to content

Instantly share code, notes, and snippets.

@wyojustin
Last active February 28, 2019 00:03
Embed
What would you like to do?
Tkinter Long Press Detector (Credit: [laurentalacoque](/laurentalacoque))
#### USAGE! Attach to self.image (not self.root) that way button clicks do not count as long presses.
#### otherwise the button call backs hang long enough to trigger the long press
## self.longpress_obj = LongPressDetector(self.image, long_press_cb)
class LongPressDetector:
"""Helper class that calls a callback after a long press/click"""
# call_back will get the long_click duration as parameter
def __init__(self, root, call_back, long_press_duration = 1000 ):
"""Creates the LongPressDetector
Arguments:
root (Tk Widget): parent element for the event binding
call_back : a callback function with prototype callback(press_duration_ms)
long_press_duration : amount of milliseconds after which we consider this press is long
"""
self.ts=0
self.root = root
self.call_back = call_back
self._suspend = False
self.long_press_duration = long_press_duration
root.bind("<Button-1>",self.__click)
root.bind("<ButtonRelease-1>",self.__release)
def suspend(self):
"""suspend longpress action"""
self._suspend = True
self.root.after_cancel(self.after_press_id)
def activate(self):
"""reactivate longpress action"""
self._suspend = False
def __click(self,event):
self.ts = event.time
if not self._suspend:
self.after_press_id = self.root.after(self.long_press_duration,
self.__trigger)
def __release(self,event):
if self.after_press_id is not None:
self.root.after_cancel(self.after_press_id)
def __trigger(self):
if self.call_back != None:
self.call_back(self.long_press_duration)
def __del__(self):
if self.after_press_id is not None:
self.root.after_cancel(self.after_press_id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment