Reputation: 403
This is my full programm(it's just for practise):
import pygame
pygame.init()
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
break
pygame.font.Font.render('Hello world', 1, (255, 100, 100))
And output is:
Traceback (most recent call last):
File "D:\Download\unim.py", line 8, in <module>
pygame.font.Font.render('Hello world', 1, (255, 100, 100))
TypeError: descriptor 'render' requires a 'pygame.font.Font' object but received a 'str'
In game pygame font is optional but it will improve game.
Upvotes: 2
Views: 5056
Reputation: 1318
You need to create your font first e.g.
myfont = pygame.font.SysFont(None,10) # use default system font, size 10
you can then do
mytext = myfont.render('Hello world', 1, (255, 100, 100))
and finally you'll need to blit mytext
to your surface and update it to display the text.
Have a look at the pygame docs as well on this: http://www.pygame.org/docs/ref/font.html
EDIT: If that's your complete script, you will need to initialise a display before your event loop:
screen = pygame.display.set_mode((300,300)) # create a 300x300 display
you can then blit your text to the screen:
screen.blit(mytext, (0,0)) # put the text in top left corner of screen
pygame.display.flip() # update the display
As the text is static, it doesn't need to be inside your while True:
loop either. You could display the text first. If you want to change the text based on an event, then this should be handled within the loop.
EDIT 2
In answer to your error message in the comments section, the issue is because some pygame commands are still running after you've issued the pygame.quit()
command. The reason for this is because your break
command only breaks the for event...
loop but you're then still inside your while True:
loop so the blit command still tries to run.
You could do it this way:
import pygame
pygame.init()
screen = pygame.display.set_mode((1200,600))
myfont = pygame.font.SysFont(None, 30)
mytext = myfont.render('Hello world', 1, (255, 100, 100))
running = True
while running:
for event in pygame.event.get():
if event.type==pygame.QUIT:
running=False
screen.fill((255, 255, 255))
screen.blit(mytext, (600, 300))
pygame.display.flip()
pygame.quit()
This should work because the main loop depends on running
being true. Hitting quit sets this to false so the script cleanly exits the while
loop and then runs the pygame.quit()
command.
Upvotes: 4