user3216654
user3216654

Reputation: 17

How to use to event handlers in one? Python

I want the end user to hit "2" to show the box, once this has been executed i would like them to hit "e" to load the other function. If i use two handler then it skips the one handling "e". Basically it skips the second if statement.

if event.type == pygame.KEYDOWN and event.key == pygame.K_2:
                highlight = pygame.image.load('Highlightmenu.png')
                highlight = pygame.transform.scale(highlight, (270, 110))
                window.blit(highlight,(316, 300))
                pygame.display.flip()
                title()
                if event.type == pygame.KEYDOWN and event.key == pygame.K_e:
                    playerNames()
                    print("Loading the player names menu...")

Upvotes: 0

Views: 84

Answers (1)

Bartlomiej Lewandowski
Bartlomiej Lewandowski

Reputation: 11180

That's because your if statement is wrong. You put the second if inside the first one. So only if the event was a KEYDOWN and key was 2, and the event was a KEYDOWN and the key was e, the statements in the second if will execute. Since a key cannot be both 2 and e, it never executes.

You should split it like this:

if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_2:
        highlight = pygame.image.load('Highlightmenu.png')
        highlight = pygame.transform.scale(highlight, (270, 110))
        window.blit(highlight,(316, 300))
        pygame.display.flip()
        title()
    elif event.key == pygame.K_e:
        playerNames()
        print("Loading the player names menu...")

It looks like you want to respond to an e key only if a 2 has been pressed before. To solve this, you need to hold a state somewhere in your program. So when the user presses 2, it changes to a different state that you can then go to different ones. For a start you can have a variable that will hold your state. Later on you can look into [state machines].1

Apart from this you also have a few issues with your code. You should not load a file from the disk each time a button is pressed. Instead, load it at the start to a dictionary, and use it when you need it. You should not do any drawing code in the event loop. The blits and the display flip should be called outside of the event loop. The event loop should only change variables that define what should be blit.

Upvotes: 2

Related Questions