1

So currently my code is

import pygame

def main():
    pygame.init()

    size = width, height = 800,700
    backgroundColor = [0, 0, 255]


    screen = pygame.display.set_mode(size)

    screen.fill(backgroundColor)

    pygame.display.flip()

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                return
            if pygame.mouse.get_pressed()[0]:
                print event.pos

main()

What I am trying to do is that while the user is holding down the mouse, the position of the cursor is being recorded. What I have works except when you click off the screen, and then click back on the screen, if gives the error:

line 23, in main print event.pos AttributeError: event member not defined

How can I have get the same results as this code gives me, but when I click off the screen, and click back on, it wont give me an error?

tysonsmiths
  • 485
  • 1
  • 8
  • 19

1 Answers1

3

Just handle the exception:

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            return
        if pygame.mouse.get_pressed()[0]:
            try:
                print event.pos
            except AttributeError:
                pass

If you print out the event itself on each iteration, you'll see that you're getting an ActiveEvent when you click onto the window, in addition to the normal MouseMotion events:

<Event(4-MouseMotion {'buttons': (0, 0, 0), 'pos': (703, 14), 'rel': (10, -12)})>
<Event(4-MouseMotion {'buttons': (0, 0, 0), 'pos': (714, 1), 'rel': (11, -13)})>
<Event(1-ActiveEvent {'state': 1, 'gain': 0})>  # clicked off
<Event(1-ActiveEvent {'state': 1, 'gain': 1})>  # clicked on

At the point you click back on, the mouse is pressed down, so you try processing the event, which throws an exception. The easiest thing is to just catch that exception when it occurs. You could also check the event type to decide whether to try printing, too.

dano
  • 91,354
  • 19
  • 222
  • 219
  • Why are you getting the mouse location from the event? I think there's a get_pos() function for this, and so you can move that code outside of the event loop entirely. Alternately, you could check for the mouse move event. – user3757614 Sep 17 '14 at 20:18
  • Because they're checking if the mouse is down, not if it's moved. – KodyVanRy Sep 18 '14 at 02:26