[英]Accessing variables from within a function
I'm displaying some stimuli and then checking for keypresses via a keypress function, but I can't seem to be able to access the variables in that function eg Quit is supposed to be initiated if the user presses Q during key checks, and if the user presses 'g', running turns to '2' which is supposed to exit the overall while loop. 我正在显示一些刺激,然后通过按键功能检查按键是否正常,但是我似乎无法访问该功能中的变量,例如,如果用户在按键检查期间按下Q,是否退出,应该退出?用户按下“ g”,运行转为“ 2”,这应该退出整个while循环。 I have tried using global variables, but I still could not get it to work, I'm also aware that global variables are considred risky.
我曾尝试使用全局变量,但仍然无法使其正常工作,我也意识到全局变量被认为具有风险。
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
Any help is appreciated. 任何帮助表示赞赏。
Since thisResp
is not defined before the check_keys()
method, the method is not going to change the value of thisRep
. 由于
thisResp
没有在之前定义check_keys()
方法,该方法不会改变的值thisRep
。 In order to change the value of thisResp
, I would either pass it as an argument to the check_keys()
, or have check_keys()
return either 1 or 0 and then set the value of thisResp
to what's return. 为了更改
thisResp
的值,我要么将其作为参数传递给check_keys()
,要么让check_keys()
返回1或0,然后将thisResp
的值设置为返回值。 Your code would look like the following using the second approach: 使用第二种方法,您的代码如下所示:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.