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:
class mywidget(Button):
def __init__(self, master):
....
self.bind('<KeyPress-b>', do_bleah)
self.bind('<KeyRelease-b>',reset_bleah)
self.reset_bleah() # must initialize the flag!
def print_bleah(self, event=None):
if self.bleahOK:
self.bleahOK = False
self.set_up_bleah()
# do other bleah-y stuff if needed
else:
self.continue_bleahing()
def reset_bleah(self, event=None):
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:
self.oldtime = 0
do_bleah(self,event=None):
if time.time() - self.oldtime > LONGENOUGH:
self.oldtime = time.time()
set_up_bleah()
else:
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