从函数内部访问变量
Accessing variables from within a function
我正在显示一些刺激,然后通过按键功能检查按键,但我似乎无法访问该功能中的变量,例如如果用户在按键检查期间按下 Q,则应该启动退出,如果用户按下 'g',运行 将变为“2”,这应该会退出整个 while 循环。我尝试过使用全局变量,但我仍然无法让它工作,我也知道全局变量被认为是有风险的。
def check_keys():
allKeys = event.getKeys(keyList = ('g','h','escape'))
for thisKey in allKeys:
if thisKey == 'escape':
dataFile.close()
window.close()
core.quit()
elif thisKey == 'g':
keyTime=core.getTime()
thisResp = 1
elif thisKey == 'h':
keyTime=core.getTime()
thisResp = 0
thisResp = 2
running = 1
while running == 1:
for frame in range(frames):
fix.draw()
upper_target.draw()
z= window.flip()
check_keys()
if thisResp == 1:
running = 2:
print running
感谢任何帮助。
由于在check_keys()
方法之前没有定义thisResp
,所以该方法不会改变thisRep
的值。为了更改 thisResp
的值,我要么将其作为参数传递给 check_keys()
,要么将 check_keys()
return 设为 1 或 0,然后设置该值thisResp
到 return。使用第二种方法,您的代码将如下所示:
def check_keys():
allKeys = event.getKeys(keyList = ('g','h','escape'))
for thisKey in allKeys:
if thisKey == 'escape':
dataFile.close()
window.close()
core.quit()
elif thisKey == 'g':
keyTime=core.getTime()
return 1
elif thisKey == 'h':
keyTime=core.getTime()
return 0
return 2
thisResp = 2
running = 1
while running == 1:
for frame in range(frames):
fix.draw()
upper_target.draw()
z= window.flip()
thisResp = check_keys()
if thisResp == 1:
running = 2
break
print running
我正在显示一些刺激,然后通过按键功能检查按键,但我似乎无法访问该功能中的变量,例如如果用户在按键检查期间按下 Q,则应该启动退出,如果用户按下 'g',运行 将变为“2”,这应该会退出整个 while 循环。我尝试过使用全局变量,但我仍然无法让它工作,我也知道全局变量被认为是有风险的。
def check_keys():
allKeys = event.getKeys(keyList = ('g','h','escape'))
for thisKey in allKeys:
if thisKey == 'escape':
dataFile.close()
window.close()
core.quit()
elif thisKey == 'g':
keyTime=core.getTime()
thisResp = 1
elif thisKey == 'h':
keyTime=core.getTime()
thisResp = 0
thisResp = 2
running = 1
while running == 1:
for frame in range(frames):
fix.draw()
upper_target.draw()
z= window.flip()
check_keys()
if thisResp == 1:
running = 2:
print running
感谢任何帮助。
由于在check_keys()
方法之前没有定义thisResp
,所以该方法不会改变thisRep
的值。为了更改 thisResp
的值,我要么将其作为参数传递给 check_keys()
,要么将 check_keys()
return 设为 1 或 0,然后设置该值thisResp
到 return。使用第二种方法,您的代码将如下所示:
def check_keys():
allKeys = event.getKeys(keyList = ('g','h','escape'))
for thisKey in allKeys:
if thisKey == 'escape':
dataFile.close()
window.close()
core.quit()
elif thisKey == 'g':
keyTime=core.getTime()
return 1
elif thisKey == 'h':
keyTime=core.getTime()
return 0
return 2
thisResp = 2
running = 1
while running == 1:
for frame in range(frames):
fix.draw()
upper_target.draw()
z= window.flip()
thisResp = check_keys()
if thisResp == 1:
running = 2
break
print running