Python/Pygame mouse position not updating and program losing focus

1.2k views Asked by At

I'm trying to learn Python/Pygame. I created a program that would use the Mouse position, but both when I run it from IDLE and from the Command prompt the mouse position doesn't update, and when I click on the graphic window it get into non-responsive mode.

The code is very simple (see below). What happens is that the print-command prints the original mouse position over and over again. Any ideas?

import pygame
from pygame.locals import *
pygame.init()
Screen = pygame.display.set_mode([1000, 600])
MousePos = pygame.mouse.get_pos()
Contin = True
while Contin:
    print(MousePos)
2

There are 2 answers

1
sPaz On BEST ANSWER

You aren't updating the MousePos to the new value, instead you are printing out same value over and over. What you would need is:

import pygame
from pygame.locals import *
pygame.init()
Screen = pygame.display.set_mode([1000, 600])
MousePos = pygame.mouse.get_pos()
Contin = True
while Contin:
    MousePos = pygame.mouse.get_pos()
    print(MousePos)
    DoSomething(MousePos)

Note: This will go into non-responsive mode as well if you dont handle any other events.

Here is a better way to handle events in PyGame:

while running:
     event = pygame.event.poll()
     if event.type == pygame.QUIT:
         running = 0
     elif event.type == pygame.MOUSEMOTION:
         print "mouse at (%d, %d)" % event.pos
0
user2746752 On

Change your while loop to this:

while Contin:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            Contin = False
    MousePos = pygame.mouse.get_pos()
    print(MousePos)