简体   繁体   中英

Pygame text input not on screen

I need to kb input onto a pygame screen at the moment it appears on the idle shell any advice would be appreciated.

This code is extracted from a larger program mostly screen based but i need to input some data (numeric) from the kb at times

import sys
import pygame
from pygame.locals import *
pygame.init()

N= ''
screen = pygame.display.set_mode((600,600))
font= pygame.font.Font(None,40)
screen.fill((255,255,255))
pygame.display.flip
pygame.display.update()


def score(C,y):
    SetWnd = font.render( C,True,(0,0,255))
    screen.blit(SetWnd, (15, 100+y))
    pygame.display.update()


def start():
    while True:
        name=''

        for evt in pygame.event.get():
                if evt.type == KEYDOWN:
                    if evt.unicode.isalnum(): # unicode
                        name+=evt.unicode
                        print name,

                    elif evt.key == K_BACKSPACE:
                            name = name[:-1]
                            print name,
                    elif evt.key == K_RETURN:
                        return N
                elif evt.type == QUIT:
                    pygame.quit()
                    sys.exit()
def Pchange(c,y):
    block = font.render(N, True, (0,0,0))
    rect = block.get_rect()
    rect.move_ip(75,100 + y)
    screen.blit(block,rect)
    pygame.display.flip()



score('wind', 0)
score('elev',20)

N = start()
Pchange(N,0)
Pchange(N,20)

Firstly you draw the score twice, which i assume works well.

The problem lies in you start function. You are not calling any draw or update function in your while loop. In your event foreach, you add a digit to name , and exit the while loop when enter is pressed. Then you draw twice with Pchange, but you are the function does not use the right parameters. You have:

def Pchange(c,y):
    block = font.render(N, True, (0,0,0))

you are using the global N which is ''. So to fix that, you need to change N to c .

The next problem is that the game quits right after pressing enter. Since you pasted only a part of the program, this might not be the case. If it is, make another while loop, and just wait for the ESC key to call pygame.quit() and sys.exit()

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