pygame text variables

Question:

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…

Asked By: user2154113

||

Answers:

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))
Answered By: Michael Mauderer
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…

Answered By: pradyunsg

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))
Answered By: Fredrik Håård

I can’t seem to do any of these. I keep getting an error : NameError: name ‘varible’ is not defined

Answered By: user22119058
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.