MojoNojo06
MojoNojo06

Reputation: 1

Pygame text not displaying

I'm new to python (and coding itself) and was trying to create a Hello World script in pygame. It's in python 3.2 and pygame 1.9.2. I have a book that I directly copied it from, but when I run it, all I get is a black window. Here is my code:

import pygame
import sys
pygame.init()
from pygame.locals import *
white = 255,255,255
blue = 0,0,200
screen = pygame.display.set_mode((600,500))
pygame.font.init
myfont = pygame.font.Font(None,60)
textImage = myfont.render("Hello Pygame", True, white)
screen.fill(blue)
screen.blit(textImage, (100,100))
pygame.display.update

The book is using the exact same versions, but I still can't get it to work.

Upvotes: 0

Views: 480

Answers (2)

Milan
Milan

Reputation: 667

There is a missing () on the update call in the last line:

pygame.display.update()

Upvotes: 0

Kingsley
Kingsley

Reputation: 14906

Ok, there's a couple of issues.

The PyGame screen update function is update(), you're missing the brackets on that call, and on the font init.

pygame.display.update()
screen = pygame.display.set_mode((600,500))
pygame.font.init()

Secondly, your program just exits straight away. You need to implement an event loop, and wait for a window-close message.

This works for me:

import sys
import pygame
from pygame.locals import *

white = 255,255,255
blue  = 0,0,200

pygame.init()
screen = pygame.display.set_mode((600,500))
pygame.font.init()
myfont = pygame.font.Font(None,60)
textImage = myfont.render("Hello Pygame", True, white)
screen.fill(blue)
screen.blit(textImage, (100,100))
pygame.display.update()

while (True):
    event = pygame.event.wait()
    if event.type == QUIT:
        pygame.quit()
        sys.exit()

I know you're just beginning, but one thing that will save you time (and make it easier) later is to put your window width & height into variables. Then position items on-screen relative to these values. That way when you change display size (or whatever) later, you need only change the code in these two places.

WIDTH  = 600
HEIGHT = 500

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
...
text_width  = textImage.get_width()
text_height = textImage.get_height()
# Centre text #TODO - handle text being larger than window
screen.blit(textImage, ( (WIDTH-text_width)//2 , (HEIGHT-text_height)//2 ))

Note: // is integer division in python

Upvotes: 1

Related Questions