I’m new to programming and I have very little knowledge of python. I’m a trying to make a program that will test auditory and visual reaction time for an experiment in biology.
For the auditory part, I’m starting the timer when the sound starts playing, the subject then has to press a key as soon as he hears it. My problem is that while the sound is still playing I can’t execute anything else and thus can’t record the time when the key is pressed.
Here’s a simplified version of what I’m trying to do:
from Tkinter import *
import time
import winsound
def chooseTest(event):
global start
if event.keysym == 'BackSpace':
root.after(2000,playSound)
elif event.keysym == 'Return':
new_time = time.clock()
elapsed = new_time - start
print elapsed
else:
pass
def playSound():
global start
start = time.clock()
winsound.PlaySound('SystemAsterisk', winsound.SND_ALIAS)
root=Tk()
root.overrideredirect(True)
root.geometry("{0}x{1}+0+0".format(root.winfo_screenwidth(),root.winfo_screenheight()))
root.bind('<Key>',chooseTest)
root.mainloop()
Whatever that I put under the elif event.keysym == ‘Return’: is only executed after that the sound is finished.
Is there some way(hopefully not very complicated) to overcome this?
The only solution that I can come up with is to take a very short sound(millisecond?) and loop it until the key is pressed.
Thank you.
You need to start the sound on a separate thread.
something like:
As a side note, having global values hanging around like this isn’t the best solution. You should read up on classes as they are a very nice way to have state shared between various function calls.