Python/Psychopy : Logging mouse click locations

标签 python psychopy

使用下面的代码,我尝试打开一个窗口 10 秒钟,让用户根据需要多次单击屏幕上的任意位置,并且我想记录鼠标单击位置。每次用户在窗口内单击(即 myMouse.getPressed)时,我都会将单击位置附加到列表中(mouse_click_locations[])。但是,该列表在每一帧上多次附加相同的单击位置。我想将单击位置追加到列表中一次,直到发起另一次单击为止。我认为在每个帧的末尾添加“myMouse.clickReset()”可以做到这一点,但这没有什么区别。

10 秒后,我希望每次启动鼠标单击时都会在列表中填充一个位置(x,y 坐标)。

from psychopy import visual, core, gui, event, sound

win = visual.Window([800,600],color=(1,1,1), colorSpace='rgb', 
rgb=None, allowGUI=True, monitor='testMonitor', 
units='deg', fullscr=False)

myMouse = event.Mouse(visible=True,win=win)

refresh_rate = 60.0
default_time = 10

time_window = default_time * refresh_rate
time_window = int(time_window)

running = 1
while running:

    mouse_click_locations = []

    for frame in range(time_window):

        mouse_loc = myMouse.getPos()
        mouse_click = myMouse.getPressed()

        if mouse_click:
            mouse_click_locations.append(mouse_loc)

        win.flip()
        myMouse.clickReset()

    running = 0

win.close()

print mouse_click_locations

有人可以帮我实现这个目标吗?我是否错误地使用了 myMouse.clickReset() ?

干杯, 乔恩

最佳答案

发生这种情况是因为脚本会检查帧循环中每次迭代的鼠标状态;即每秒 60 次。正如您所说,您只想为每次鼠标按下获取一个事件。这是一种解决方案,您只需停止脚本,直到释放所有按钮即可。另请注意使用 any 显式检查所有按钮。

# Record mouse position if a key is pressed
if any(myMouse.getPressed())  # Any button pressed, no matter which
    mouse_click_locations.append(myMouse.getPos())

# Wait until all buttons are released
while any(myMouse.getPressed()):
    pass

无需使用mouse.clickReset。作为一个小注释,您不会更新屏幕上的视觉内容,因此您不需要在循环中包含 win.flip 。因为它等待下一次监视器更新,所以它有效地将 react 时间(如果您需要这些)四舍五入到最接近的 1/60 秒间隔。这一点,并且稍微依赖默认值,也会大大简化脚本:

default_time = 10

from psychopy import visual, core, event    
win = visual.Window(color='white', monitor='testMonitor', units='deg')
myMouse = event.Mouse(visible=True, win=win)
clock = core.ClocK()

# Collect unique click events before time runs out
mouse_click_locations = []
while clock.getTime() < default_time:
    # Record mouse position if a key is pressed
    if any(myMouse.getPressed())  # Any button pressed, no matter which
        mouse_click_locations.append(myMouse.getPos())

    # Wait until all buttons are released
    while any(myMouse.getPressed()):
        pass

print mouse_click_locations

关于Python/Psychopy : Logging mouse click locations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44355209/

相关文章:

python - PsychoPy 使用随机点运动图 (RDK) 模拟扩展焦点

python - 如何在Python脚本中实现触发器

python - 为什么 QuickSort 的这种实现不起作用?

python - 在 psychopy 的 while 循环中只写出第一个结果

python - Nixos 中 python 包集合的正确程序

python - 您如何在 PsychoPy Builder 中实现条件分支实验?

python - pip:有什么解决方法可以避免 --allow-external?

python - 如何修复 Sagemath 中函数 mod 的错误?

python - Lilipse/Eclipse : setup debugging environment for a django project alongwith its virtualenv

python - 什么控制 Tkinter 中的自动窗口大小调整?