简体   繁体   中英

Python: Why is pygame.event.key.get_pressed() not working?

I have been trying to make it where if i press space when the program has already been launched it will play my song. It opens up, then i get the loading animation on my cursor(when cursor is over the program.).The programs crashed.

`import pygame, sys
from pygame.locals import *
bf = 'bg.jpg'
pygame.init()
screen = pygame.display.set_mode((800, 600))
background = pygame.image.load(bf) .convert()
screen.blit(background, (0,0))
pygame.display.update()
pygame.display.set_caption('Letters')
keys=pygame.key.get_pressed()


while True:
    if keys[pygame.K_SPACE]:
        pygame.mixer.music.load('ht.mp3')
        pygame.mixer.music.play(loops=-1, start=0)


running = True
while running:
    for event in pygame.event.get():
        if event.type == QUIT:

            pygame.quit()
            sys.exit()

Please explain it me like I was a kid.(I am new in pygame.)

Your program is stuck here:

while True:
    if keys[pygame.K_SPACE]:
        pygame.mixer.music.load('ht.mp3')
        pygame.mixer.music.play(loops=-1, start=0)

The loop never ends. Once you obtain the condition you needed, you should break the loop:

while True:
    if keys[pygame.K_SPACE]:
        pygame.mixer.music.load('ht.mp3')
        pygame.mixer.music.play(loops=-1, start=0)
        break

Or just remove the while loop altogether, you don't seem to need it:

if keys[pygame.K_SPACE]:
    pygame.mixer.music.load('ht.mp3')
    pygame.mixer.music.play(loops=-1, start=0)

Hope this helps!

You don't receive events because of pygame doesn't started. If you remove your while True loop then pygame will start and begin to receive events

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM