【问题标题】:How to change text in pygame? [duplicate]如何在pygame中更改文本? [复制]
【发布时间】:2021-09-07 23:36:33
【问题描述】:

我尝试更改显示的文本,但没有成功。我该如何改变它? 我试图做改变的变量。这是我的代码。超级乱,但我希望你知道如何提供帮助。

import pygame
import os
pygame.font.init()

FONT = pygame.font.SysFont('comicsans', 100)

SCREENX = 1700
SCREENY = 900

WHITE = (255, 255, 255)

x = 0
TEXT = FONT.render(str(x), 1, (255, 255, 255))

WIN = pygame.display.set_mode((SCREENX, SCREENY))
BACKGROUND = pygame.transform.scale(pygame.image.load(
    os.path.join('Assets', 'space.png')), (SCREENX, SCREENY))


def draw_window():
    WIN.blit(BACKGROUND, (0, 0))
    TEXT = FONT.render(str(x), 1, (255, 255, 255))
    WIN.blit(TEXT, ((SCREENX - TEXT.get_width()) /
         2, (SCREENY - TEXT.get_height()) / 2))
    pygame.display.update()


def main():
    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    x += 1
                
        draw_window()
    pygame.quit


if __name__ == '__main__':
    main()

所以当我按空格键时,它会显示:UnboundLocalError: local variable 'x' referenced before assignment。

你能帮忙吗?我从谷歌上看过,但我没有看到像我这样的问题。我使用 VS 代码。

【问题讨论】:

  • 除了错误之外,还有一个错字。 pygame.quit 必须是 pygame.quit()

标签: python text pygame render


【解决方案1】:

如果您想在函数内更改全局命名空间中的变量,您必须使用global statement

def main():
    global x # <--- this is missing

    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    x += 1
                
        draw_window()
    pygame.quit()

【讨论】:

    猜你喜欢
    • 2018-04-29
    • 2014-01-17
    • 1970-01-01
    • 2019-05-23
    • 2022-01-22
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多