shafty
shafty

Reputation: 605

pygame mouse.get_pos() not working

I can't get a very simple pygame script to work:

import pygame

class MainWindow(object):

    def __init__(self):
        pygame.init()

        pygame.display.set_caption('Game')
        pygame.mouse.set_visible(True)
        # pygame.mouse.set_visible(False) # this doesn't work either!

        screen = pygame.display.set_mode((640,480), 0, 32)

        pygame.mixer.init()

        while True:
            print pygame.mouse.get_pos()

        pygame.mixer.quit()
        pygame.quit()

MainWindow()

This just outputs (0,0) as I move the mouse around the window:

(0, 0)
(0, 0)
(0, 0)
(0, 0)
(0, 0)

Can anyone check this?

Edit - fixed code:

import pygame

class MainWindow(object):

    def __init__(self):
        pygame.init()

        pygame.display.set_caption('Game')
        pygame.mouse.set_visible(True)
        # pygame.mouse.set_visible(False) # this doesn't work either!

        screen = pygame.display.set_mode((640,480), 0, 32)

        pygame.mixer.init()

        while True:
            for event in pygame.event.get():
                if event.type == pygame.MOUSEMOTION:
                    print pygame.mouse.get_pos()

        pygame.mixer.quit()
        pygame.quit()

MainWindow()

Upvotes: 4

Views: 7713

Answers (2)

Imre Kerr
Imre Kerr

Reputation: 2428

Pygame will constantly dispatch events while it's running. These need to be handled in some way or pygame will hang and not do anything. Simplest way to fix it is by adding this to your main loop:

...
    while True:
        for event in pygame.event.get():
            pass                                             
        print pygame.mouse.get_pos()
...

Upvotes: 5

Paco
Paco

Reputation: 4698

I never used this before, but I found that

Pygame: Mouse Specific Axis Detection

You need to wait until an event happens. I assume this empties the stack and allows you to get the data later on.

for event in pygame.event.get()

Upvotes: 1

Related Questions