Search code examples
pythonpython-3.xpygamekeyboard

Get Key Press in Python (pygame)


I have a python program that displays photos in a random order, using pygame to display them. I would like to use fullscreen, but as far as I know there is no easy way to exit the fullscreen window without removing the power from my raspberry pi (causing severe problems). I want to create a block of code that constantly polls for a key press, and when it detects one kills the program using quit()

I have already tried implementing this and this but I can't get them to work without errors.

gameDisplay = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE)
events = pygame.event.get()
#get a random line from the txt file (imgs.txt)
def random_line():
    line_num = 0
    selected_line = ''
    with open('imgs.txt') as f: 
        while 1:
            line = f.readline()
            if not line: break
            line_num += 1
            if random.uniform(0, line_num) < 1:
                selected_line = line
    return selected_line.strip()
while True:       
    img_r = pygame.image.load(random_line())
    img_r = pygame.transform.scale(img_r, (1280, 1024))
    gameDisplay.blit(img_r, (0, 0)) #Replace (0, 0) with desired coordinates
    pygame.display.flip()
    time.sleep(1)

accidentally deleted my old code that had errors, but here are the errors

Traceback (most recent call last):
  File "/home/pi/Photo Frame/Photo Frame V1.0.py", line 29, in <module>
    GPE = get_pygame_events()
NameError: name 'get_pygame_events' is not defined

I expected the window to quit when I pressed the w key (that was the key I was trying to poll)

If you need more info, just ask

also, I am running raspbian lite with a manually installed GUI, if that affects anything.


Solution

  • I expected the window to quit when I pressed the w key (that was the key I was trying to poll)

    All you've to do is to add an event loop. If w is pessed the switch a state which terminates the program:

    run = True
    while run:
    
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
    
            # set "run = False" if "w" is pressed
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w:  
                    run = False
    
        # [...]
    
    pygame.quit()