Pygame:font.render() 给出“类型错误:前景 RGBA 参数无效”

问题描述

我尝试使用 screen.blit() 创建一个总点击次数栏(我也希望它在您点击时更新文本),我尝试过

text = font.render('Your total clicks are',totalbal,True,WHITE)

但它不起作用

line 21,in <module>
    text = font.render('Your total clicks are',WHITE)
TypeError: Invalid foreground RGBA argument

我也用 str(totalbal) 试过了,但还是不行。

import pygame,sys,time
from pygame.locals import *

pygame.init()
WHITE = 255,255,255
font = pygame.font.SysFont(None,44)
baltotal = open("totalbal.txt","r+")
totalbal = int(baltotal.read())
w = 800
h = 600
screen = pygame.display.set_mode((w,h))
Loop = True
text = font.render('Your total clicks are',WHITE)
while Loop: # main game loop
    ...

        if event.type == MOUSEBUTTONDOWN: #detecting mouse click
                totalbal += cps
                print("Your total clicks are",end="\r")
    ...
    screen.blit(text,(235,557))
    pygame.display.flip()
    pygame.display.update()
    clock.tick(30)

with open("totalbal.txt","w") as baltotal:
    baltotal.write(str(totalbal))
baltotal.close

pygame.quit()
sys.exit()

解决方法

你必须连接字符串

text = font.render('Your total clicks are ' + str(totalbal),True,WHITE)

或使用 formatted string literals

text = font.render(f'Your total clicks are {totalbal}',WHITE)

如果文本发生变化,则需要再次渲染文本Surface

text = font.render(f'Your total clicks are {totalbal}',WHITE)
while Loop: # main game loop
    # [...]

    for event in pygame.event.get():

        if event.type == MOUSEBUTTONDOWN: #detecting mouse click
            totalbal += cps
            text = font.render(f'Your total clicks are {totalbal}',WHITE)

    # [...]