简体   繁体   中英

`pygame.mouse.get_pressed()` reports clicks when mouse is not clicked

I am programming an experiment with Pygame 1.9.2 on Python 2.7. In the experiment, I display an image and ask the user to click either the left mouse button or right mouse button based on a feature of the image (I instruct them in advance when to click what). The image is displayed until the user clicks or if the time of image display exceeds a fixed duration.

Here's the code snippet.(Hope this bit is enough to understand what is being done.)

pygame.display.update()
resp = None
while 1:
    dispEnd = time.time()
    pygame.mouse.set_visible(True)    
    pygame.event.get()
    ms = pygame.mouse.get_pressed()            
    if ms[0] or ms[2]:
        rt = dispEnd - dispSt                
        if ms[0]:
            resp = 'Yes'
        else:
            resp = 'No'
        break
    if dispEnd - dispSt >= changeDuration:
        break

This piece of code is part of a bigger loop where an image is selected and displayed, so this runs several times.

What happens at unpredictable times is that the program does not wait for user input. Right after displaying the image, it enters the while loop and proceeds as if the mouse were pressed.

It's a random error and happens anytime; sometimes right at the start of the program, from the very first run of the loop; so probably it is not because of the event queue possibly not being cleared (which it is while calling pygame.event.get() ) and it also cannot be defaulting to the previous mouse click; sometimes it happens after a few iterations of the loop. Either way, it is disastrous for an experiment.

Try this out:

...
while 1:
    dispEnd = time.time()
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN: 
            #do something           
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM