View Single Post
Join Date: Jul 2006
Posts: 608
Reputation: jrcagle is on a distinguished road 
Solved Threads: 150
jrcagle jrcagle is offline Offline
Practically a Master Poster

Re: KeyPress event with holding down the key

 
0
  #3
Feb 22nd, 2007
In elec eng., this problem is called 'key debouncing.' When I type here at the keyboard, the keyboard device (or its driver) has to decide whether my keypresses that last tens of milliseconds ... practically forever! ... are supposed to be single keypresses or multiple presses or press-and-hold.

The usual way to solve the problem in software is to put a flag or timer on the key.

The flag system is tied to events: if the action is supposed to take place on a single keypress, then set a flag when the action starts and clear it when the action stops. Here's one possibility:

  1. class mywidget(Button):
  2. def __init__(self, master):
  3. ....
  4. self.bind('<KeyPress-b>', do_bleah)
  5. self.bind('<KeyRelease-b>',reset_bleah)
  6. self.reset_bleah() # must initialize the flag!
  7.  
  8. def print_bleah(self, event=None):
  9. if self.bleahOK:
  10. self.bleahOK = False
  11. self.set_up_bleah()
  12. # do other bleah-y stuff if needed
  13. else:
  14. self.continue_bleahing()
  15.  
  16. def reset_bleah(self, event=None):
  17. self.bleahOK = True

This way, the initial press sets up the action, but subsequent holding causes the action to continue. Basically, your function acts like two functions in one. It has one action on first keypress and a different action on key-holding.

You may recognize the flag as similar to a lock as used in threaded programs.

A second way to solve this for real-time systems (like pygame) is to set a timer of sorts:

  1. self.oldtime = 0
  2. do_bleah(self,event=None):
  3. if time.time() - self.oldtime > LONGENOUGH:
  4. self.oldtime = time.time()
  5. set_up_bleah()
  6. else:
  7. continue_bleahing()

Here, you impose a delay by setting oldtime when the button is first pressed and requiring that the next registered press be at least LONGENOUGH later.

IMO, this might be quirky in a system like Tkinter where the results of your keypress might not be finished when time is up. So I would probably go for the flag system with Tkinter and the timer system with something like pygame.

Jeff
Last edited by jrcagle; Feb 22nd, 2007 at 11:58 pm.
Reply With Quote