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)
有帮助吗?

解决方案

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

其他提示

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)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top