Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to detect if a user has typed an integer on their keyboard in pygame?

I am making a Calculator with Pygame and I want to check if the user has pressed a key which is an integer. If the key is an integer like 1 or 2 then blit the number onto the screen.
I have tried but many times but failed

Here’s my code

import pygame, math

pygame.init()
screen_width = 1200
screen_height = 500
gameWindow = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Calculator')
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
white = (255, 255, 255)
black = (0, 0, 0)
grey = (128, 128, 128)
font = pygame.font.SysFont('comicsans', 40)
fps = 60
clock = pygame.time.Clock()

def text_screen(text, color, x, y):
     screen_text = font.render(text, True, color)
     gameWindow.blit(screen_text, [x ,y])

def welcome_screen(run):
    clock.tick(fps) 
    gameWindow.fill(grey)
    while not run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                 run = True
            if event.type == pygame.KEYDOWN:
                if event.key == # Code to check whether the key is integer or not:
                     pass
        pygame.display.update()

def gameLoop(run):
    clock.tick(fps)
    gameWindow.fill(grey)
    while not run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = True
        pygame.display.update()

if __name__ == "__main__":
    welcome_screen(False)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could convert the keycode to representing character, then check if that is a digit with isdigit().

if event.type == pygame.KEYDOWN:
    if pygame.key.name(event.key).isdigit():
        pass # Do stuff
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading