2

I'm using PyGame on Ubuntu and I want to make a while loop that ends when the user presses any button on the keyboard.

This code does not leave the loop, and Eclipse gives no errors and no warnings but never leaves the loop. What is wrong?

import time
import pygame
pygame.init()

test = False

while not test:
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            print "gotcha"
            test = True;
            break;

    print "Still looping"
    time.sleep(1);



print "made it out of the loop" ;

Ideally every second "still loopin" should be printed to the screen until I press any key, when "made it out of the loop" should be printed.

This doesn't happen: the loops continues forever (until I terminate the script).

1
  • FYI you don't need semicolons at the end of the line for Python. It's not invalid, just unnecessary. Commented Aug 12, 2014 at 12:03

1 Answer 1

3

You need to

According to the game programming wiki: If you do not set a pygame display pygame screen, no input will get to pygame's event handling.

import time

import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Pygame Caption')

test = False

while not test:
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            print "gotcha"
            test = True
            break

    print "Still looping"
    time.sleep(1)

print "made it out of the loop" 
Sign up to request clarification or add additional context in comments.

4 Comments

No worries, you're welcome. I am not pygame expert but that seems to be the way to go.
Also, if you don't want a display you can use a dummy variable so that you're still able to capture events without creating a window. There's an example on the Pygame wiki.
@elParaguayo, the example you linked says: "Warning: Unfortunately events would not not be available with dummy videodriver, so you could not use eg. pygame keys module in headless mode."
@Vectornaut: Thanks for your comment. I don't know about keypresses so you may well be right, but I thought you could still use the event queue (e.g. for posting and acting on pygame.USEREVENT).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.