2

My question is all I want to do is display text on the screen in pygame. If someone known how to do this please tell me!

My code

import time
import pygame
from pygame.locals import *
pygame.init
blue = (0,0,255)
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 500
WINDOW = pygame.display.set_mode((WINDOW_WIDTH,WINDOW_HEIGHT))
pygame.display.set_caption("Text")
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit
            exit()
    font = pygame.font.SysFont(None, 25)
    def show_text(msg,color):
        text = font.render(msg,True,color)
        WINDOW.blit(text,[WINDOW_WIDTH/2,WIDTH_HEIGHT/2])
        show_text("This is a message!", blue)
    pygame.display.update()

I want to just make text that says "This is a message!". That is all

Kingsley
  • 14,398
  • 5
  • 31
  • 53
Ravishankar D
  • 131
  • 10

1 Answers1

3

You are pretty close already. To render text you need to first define a font, then use it to render(). This creates a bitmap with the text in it, which needs to be blit() to the window.

All the necessary parts are in the question-code, they are just a bit mixed-up.

import time
import pygame
from pygame.locals import *

# Constants
blue = (0,0,255)
WINDOW_WIDTH  = 500
WINDOW_HEIGHT = 500

def show_text( msg, color, x=WINDOW_WIDTH//2, y=WINDOW_WIDTH//2 ):
    global WINDOW
    text = font.render( msg, True, color)
    WINDOW.blit(text, ( x, y ) )

pygame.init()
WINDOW = pygame.display.set_mode((WINDOW_WIDTH,WINDOW_HEIGHT))
pygame.display.set_caption("Text")

# Create the font (only needs to be done once)
font = pygame.font.SysFont(None, 25)

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

    WINDOW.fill( ( 255, 255, 255 ) )   # fill screen with white background

    show_text("This is a message!", blue)

    pygame.display.update()
Kingsley
  • 14,398
  • 5
  • 31
  • 53
  • Oh thx a lot you have been answering a lot of my questions recently and I really appreciate it! Also really nice and simple code you gave me I really liked it! – Ravishankar D Sep 22 '20 at 01:04