Reputation: 383
I'm learning to use pygame and I have some problems with rendering text.
The simplified code I'm working with is like this:
import pygame
sizex =200; sizey =200
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((sizex,sizey))
myfont = pygame.font.Font(None, 32)
score=pygame.Rect(100,100,100,50)
screen.fill((255,255,255))
pygame.draw.rect(screen, (0,250,0), (10,10,10,10), 2)
pygame.display.update()
for i in xrange(0,1000):
msElapsed = clock.tick(2)
text="I = %d" %i
label = myfont.render(text, 1, (0,0,250))
screen.blit(label, (100, 100))
pygame.display.update(score)
I want update only the part of screen which contains the textbox. But this code is not doing this. The texts overwrite themselves and become unreadable after a while.
What am I doing wrong?
Upvotes: 3
Views: 1686
Reputation: 59701
The problem is that when you blit a text, the background of the text is transparent (note that this important for example when you want to have a background image). You have to "clear" the rectangle first, and then blit the text. In your case, as you are using a plain color as background, you can do:
for i in xrange(0,1000):
msElapsed = clock.tick(2)
text="I = %d" %i
label = myfont.render(text, 1, (0,0,250))
screen.fill((255,255,255), rect=label.get_rect(topleft=(100,100)))
screen.blit(label, (100, 100))
pygame.display.update(score)
If you use an image instead of a solid color, you would have to blit the appropriate area of the background.
Edit:
As indicated by Bartlomiej, if the new string is sorter than the former, it will not get erased completely. You may just clear the whole screen each time, or try to figure out how to clear exactly what you need to clear, for example, storing the area of the previous blit:
previous_rect = None
for i in xrange(0,1000):
msElapsed = clock.tick(2)
text="I = %d" %i
if prev_rect:
screen.fill((255,255,255), rect=prev_rect)
label = myfont.render(text, 1, (0,0,250))
previous_rect = label.get_rect(topleft=(100,100))
screen.blit(label, (100, 100))
pygame.display.update(score)
Upvotes: 1