psychopy.org | Reference | Downloads | Github

Mouse click on a shape with an alternative not working

from psychopy import visual,event,core,gui

#creating a window
win = visual.Window(
                    size=[1080, 720],
                    units="pix",
                    fullscr=True,
                    color=[1, 1, 1]
                )
mouse = event.Mouse()#initializing mouse event

#shape on which mouse is to be clicked                
rect = visual.Rect(
                    win=win,
                    units="pix",
                    width=200,
                    height=240,
                    fillColor=[1, 1, -1],
                    lineColor=[-1, 1, 1],
                    pos=(0.0,0.0),
                    lineWidth=5.0
                )
#modified shape upon mouse click
rect1 = visual.Rect(
                    win=win,
                    units="pix",
                    width=200,
                    height=240,
                    fillColor=[-1, 1, 1],
                    lineColor=[-1, 1, 1],
                    pos=(0.0,0.0),
                    lineWidth=5.0
                )

rect.draw()
win.flip()
while True:
    if mouse.isPressedIn(rect):      #if shape is clicked rect2 should be drawn
        rect1.draw()
        win.flip()
        print("clicked")
        break
    else:
        event.waitKeys()        #if a key is pressed instead of mouse click the program should end
        break

On running the code, only the else part runs. The shape cannot be mouse clicked but a key can be pressed.

If I understand your code correctly you can only click the rect if you are press the key while you are holding down the mouse button. The code will spend most of its time waiting for the next key.

No, I can only press the key. I am not able to click the rectangle through mouse.

On second looking it won’t loop back after the first key press so you’d need to be clicking on the rectangle on the first frame.

Basically I think you need to have something like while len(event.getKeys())==0: check the mouse.

I guess you are not getting the actual issue. On running the code, the user should have an option between “clicking the rectangle” and “press any key”. However, this code does not allow to click the rectangle, but only press a key.
Anyways, I tried while len(event.getKeys())==0: check the mouse, but it doesn’t help.

It’s true that I am missing how you think the computer will interpret the code as the behaviour you want (which I do understand). I think that if you put print(“unclicked”) below while True: (indented of course) you will only get a single log of unclicked per keyboard press.

Ok, I got your point now. :slight_smile:
So, how shall we implement my requirement where a user can choose between a mouse click and a key press?

Try getKeys instead of waitKeys. I’m not sure of the exact syntax.

Yeah, it worked. Thanks a lot. :slight_smile: