九歌当下 发表于 2024-12-28 09:55:04

pygame导入系统字体后无法显示文字

import pygame
import random
pygame.init()
screen = pygame.display.set_mode()
pygame.display.set_caption("test1")
font = pygame.font.SysFont("微软雅黑", 24)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
posx = 50
posy = 50
xvel = 3
yvel = 3
keep_going = True
times = 0
clock = pygame.time.Clock()
while keep_going:
    for event in pygame.event.get():
      if event.type == pygame.QUIT:
            keep_going = False
    print_text = f"the hit times -- {times}"
    text = font.render(print_text, True, WHITE)
    text_rect = text.get_rect()
    text_rect.centerx = screen.get_rect().centerx
    text_rect.y = 50
    screen.blit(text, text_rect)
    posx += xvel
    posy += yvel
    if posx <= 50 or posx >= 750:
      xvel = -xvel
      times += 1
    if posy <= 50 or posy >= 550:
      yvel = -yvel
      times += 1
    screen.fill(BLACK)
    pygame.draw.circle(screen, RED, (posx, posy), 50)
    pygame.display.update()
    clock.tick(60)
pygame.quit()

运行后屏幕上方没有显示文字,请求帮助

FishC 发表于 2024-12-28 09:55:13

以下是你代码中可能导致文字无法显示的问题以及解决方案:

1. **更新屏幕顺序错误:**
   你在更新屏幕内容(`pygame.display.update()`)之前调用了`screen.fill(BLACK)`,这会覆盖之前绘制的文字。因此,你需要先清屏,再绘制文字和其他元素,然后更新显示。

2. **`if`条件错误:**
   条件判断中的`=`应该是`==`。使用单个`=`进行赋值会导致语法错误。应当用`==`来进行条件判断。

修改后的代码如下:

import pygame
import random
pygame.init()
screen = pygame.display.set_mode((800, 600))# 指定窗口大小
pygame.display.set_caption("test1")
font = pygame.font.SysFont("微软雅黑", 24)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
posx = 50
posy = 50
xvel = 3
yvel = 3
keep_going = True
times = 0
clock = pygame.time.Clock()
while keep_going:
    for event in pygame.event.get():
      if event.type == pygame.QUIT:
            keep_going = False

    # 先填充背景色
    screen.fill(BLACK)

    # 更新文字
    print_text = f"the hit times -- {times}"
    text = font.render(print_text, True, WHITE)
    text_rect = text.get_rect()
    text_rect.centerx = screen.get_rect().centerx
    text_rect.y = 50
    screen.blit(text, text_rect)

    # 更新圆的信息
    posx += xvel
    posy += yvel
    if posx == 750 or posx == 0:# 使用==进行比较
      xvel = -xvel
      times += 1
    if posy == 550 or posy == 0:# 使用==进行比较
      yvel = -yvel
      times += 1

    # 绘制圆
    pygame.draw.circle(screen, RED, (posx, posy), 50)
   
    # 更新显示内容
    pygame.display.update()
    clock.tick(60)
pygame.quit()

希望对你有所帮助!如果还有其他问题,请随时问。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
页: [1]
查看完整版本: pygame导入系统字体后无法显示文字