Reputation: 13
I have a button created with pygame. Now i want to show some text on screen once the button is pressed. But i want to give it a varibale instead of string. How do i do that ? I tried adding the screen.blit(txtSmjerKretanja, (150,150))
to if gumbLijevo.collidepoint(mouse_pos)
and if gumbDesno.collidepoint(mouse_pos):
but it doesn't work.
EDIT:
I looked at the suggested topics from other users, but it doesn't really solve my problem. Problem is that my program doesn't show text as soon as i use some varibale (in this case smjerKretanja) instead of usual string like ('some string..').
import pygame
import sys
def main():
pygame.init()
myfont = pygame.font.SysFont('Arial', 20)
clock = pygame.time.Clock()
fps = 60
size = [500, 500]
bg = [255, 255, 255]
smjerKretanja = 0
screen = pygame.display.set_mode(size)
gumbLijevo = pygame.Rect(20, 20, 100, 30)
gumbDesno = pygame.Rect(150, 20, 100, 30)
txtLijevo = myfont.render('Lijevo', False, (0,0,0))
txtDesno = myfont.render('Desno', False, (0,0,0))
txtSmjerKretanja = myfont.render(str(smjerKretanja), False, (0,0,0))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return False
if event.type == pygame.MOUSEBUTTONDOWN:
mouse_pos = event.pos # gets mouse position
# checks if mouse position is over the button
if gumbLijevo.collidepoint(mouse_pos):
# prints current location of mouse
# print('button was pressed at {0}'.format(mouse_pos))
smjerKretanja = smjerKretanja - 10
if smjerKretanja < 0:
smjerKretanja = 350
print smjerKretanja
screen.blit(txtSmjerKretanja, (150,150))
if gumbDesno.collidepoint(mouse_pos):
# prints current location of mouse
# print('button was pressed at {0}'.format(mouse_pos))
smjerKretanja = smjerKretanja + 10
if smjerKretanja > 360:
smjerKretanja = 10
print smjerKretanja
screen.blit(txtSmjerKretanja, (150,150))
screen.fill(bg)
pygame.draw.rect(screen, [255, 0, 0], gumbLijevo)
pygame.draw.rect(screen, [255, 0, 0], gumbDesno)
screen.blit(txtLijevo,(30,20))
screen.blit(txtDesno,(160,20))
pygame.display.update()
clock.tick(fps)
pygame.quit()
sys.exit
if __name__ == '__main__':
main()
Upvotes: 1
Views: 1199
Reputation: 310
You only update txtSmjerKretanja at the start of the code, in order to update it constantly you need to add
txtSmjerKretanja = myfont.render(str(smjerKretanja), False, (0,0,0))
the while loop
Upvotes: 0