如何使用 pygame 将变量的值显示为文本

How to display the value of a variable as text using pygame

我正在使用 Windows 10 和 Python 3.7 以及 pygame 1.9.4。

我的应用程序要求将变量的值显示在 pygame 屏幕上。

目前,我有:

tnr = pygame.font.SysFont('Times New Roman', 30)
text2 = tnr.render(timePriorities, False, (0, 0, 0))
screen.blit(text2,(0,0))

这会输出此错误:

TypeError: text must be a unicode or byte

有谁知道如何解决这个问题?

谢谢!

哦,这是相关代码:

timePriorities = 1.1
timeRightTurn = 2.2
timeDeadEnd = 3.3
timeIntersection = 4.4
array = sorted([timePriorities,timeRightTurn,timeDeadEnd,timeIntersection])
arrayLength = len(array)
tnr = pygame.font.SysFont('Times New Roman', 30)
for i in range(0,arrayLength):
    if timePriorities == array[i]:
        str(timePriorities)
        text1 = tnr.render('Priorities', False, (0, 0, 0))
        text2 = tnr.render(timePriorities, False, (0, 0, 0))
    else:
        if timeRightTurn == array[i]:
            str(timeRightTurn)
            text3 = tnr.render('Right Turn', False, (0, 0, 0))
            text4 = tnr.render(timeRightTurn, False, (0, 0, 0))
        else:
            if timeDeadEnd == array[i]:
                str(timeDeadEnd)
                text5 = tnr.render('Dead End', False, (0, 0, 0))
                text6 = tnr.render(timeDeadEnd, False, (0, 0, 0))
            else:
                if timeIntersection == array[i]:
                    str(timeIntersection)
                    text7 = tnr.render('Intersection', False, (0, 0, 0))
                    text8 = tnr.render(timeIntersection, False, (0, 0, 0))

问题在于 str(timePriorities) 不会将 timePriorities 更改为字符串,它 returns 将值更改为字符串。

你需要这样赋值:

timePriorities = str(timePriorities) 

或者,您可以像这样在渲染中执行此操作:

text2 = tnr.render(str(timePriorities), False, (0, 0, 0))