user2154113
user2154113

Reputation: 411

pygame text variables

I'm having trouble with pygame...again...one of these days I swear I'll be good enough to not have to come here for easy answers...

Anyway, the problem this time is I'm trying to print text on the screen with a variable inside it.

wordfont = pygame.font.SysFont("sans",12)

class Status:

    def __init__(self):
        self.a=30

    def showme(self):
        health = wordfont.render(("Your health: ", self.a,), 1, (255, 9, 12))
        screen.blit(health, (150, 150))

It says that it has to be a string or unicode...but maybe there is some way? Once again, I remind everyone to not correct anything that I'm not asking about. I know there is probably some easier way to do these things...

Upvotes: 3

Views: 4840

Answers (3)

Michael Mauderer
Michael Mauderer

Reputation: 3872

You are passing the tuple ("Your health: ", self.a,) as the first argument to render. I'm assuming there should be a string instead.

There are several ways to format a string with a variable, one approach is this:

msg = "Your health: {0}".format(self.a)
health = wordfont.render(msg, 1, (255, 9, 12))

Upvotes: 1

Fredrik Håård
Fredrik Håård

Reputation: 2915

You want to send a string instead of a tuple to render as first argument:

health = wordfont.render("Your health: " + str(self.a), 1, (255, 9, 12))

Upvotes: 1

pradyunsg
pradyunsg

Reputation: 19406

health = wordfont.render(("Your health: ", self.a,), 1, (255, 9, 12))

Should be

health = wordfont.render("Your health: {0}".format(self.a), 1, (255, 9, 12))

or

health = wordfont.render("Your health: %s" % self.a), 1, (255, 9, 12))

("Your health: ", self.a,) is a tuple. By passing a string, you can solve your problem.

See here to understand what I have done...

Upvotes: 1

Related Questions