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!