Problem with pygame.key.get_pressed() (orientation perception task)

Hi everybody,

In a part of our orientation perception experiment, we first show an oriented line to the subjects then we ask them to report its orientation on the next screen. To do that I have added these lines of code in the frame.tab:

pygame.event.pump() 

pressed = pygame.key.get_pressed()

if pressed[pygame.K_LEFT]:
        BO -= 1
        thisExp.addData('adj_final_ori',BO)


if pressed[pygame.K_RIGHT]:
        BO += 1 
        thisExp.addData('adj_final_ori',BO)

everything works fine, and I can adjust the orientation of the line when I hold down the Left or Right keys, but the problem is that some times(not always) even after releasing the key the line keeps rotating and I have to push the same key to stop it. Any Idea how to solve this problem?

Are you using Pygame windows specifically? By default PsychoPy uses pyglet, so I’m not even sure how pygame would be working here.

I have a pyglet solution for detecting keys being held down. Assuming you have made a pyglet window called win and assuming K_LEFT and K_RIGHT are the arrow keys:

key = pyglet.window.key  
keyboard = self.key.KeyStateHandler()
win.winHandle.push_handlers(self.keyboard)

if keyboard[key.LEFT]:
    BO -= 1
    thisExp.addData('adj_final_ori',BO)

if keyboard[key.RIGHT]:
    BO += 1 
    thisExp.addData('adj_final_ori',BO)

Unfortunately, if you are using a pygame window specifically, I have no idea because I don’t know how it handles events, but it’s something about the keyboard buffer failing to clear. One of the nice things about the pyglet solution is that it just gets all keyboard events pushed to it on every frame anyways.

1 Like

Thank you Jonathan for your answer. Actually I used pygame because I couldn’t manage to use pyglet! I tried your solution and I got this error :

keyboard = self.key.KeyStateHandler()
NameError: name ‘self’ is not defined

These are my begin Routine and Each Frame tabs:

Whoops, sorry! That’s my bad. I copied this from a more complex piece of code that has object structure, the ‘self’ thing I forgot to delete. Drop the ‘self’ altogether from wherever it shows up. Here’s fixed code:

key = pyglet.window.key  
keyboard = key.KeyStateHandler()
win.winHandle.push_handlers(keyboard)

if keyboard[key.LEFT]:
    BO -= 1
    thisExp.addData('adj_final_ori',BO)

if keyboard[key.RIGHT]:
    BO += 1 
    thisExp.addData('adj_final_ori',BO)

EDIT: Also you should put the first part in “begin routine” or “begin experiment”, and only the if statements on each frame.

Now it works very well!
Thank you so much!