You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pygame中q1Text文本无法渲染显示问题求助

问题分析与修复方案

嘿,这问题一眼就能看出来啦!你确实通过font.render()生成了文本对象,但漏掉了把它绘制到窗口的关键步骤——只创建了q1Text却没调用win.blit()把它放到屏幕上,所以文本自然不会显示出来。

修复后的完整代码

import pygame
import random
pygame.init()
#Title
pygame.display.set_caption('Average Speed Game')
#Screen
screenWidth=900
screenHeight=500
win=pygame.display.set_mode((screenWidth,screenHeight))
#Framerate
clock= pygame.time.Clock()
#background image
bg=pygame.image.load('C:\\Users\\18597\\Desktop\\My Python Scripts\\speed\\bg.png')
class question(object):
    def __init__(self,q,a,b,c,d):
        self.a=a
        self.b=b
        self.c=c
        self.d=d
        self.q=q
def redrawGameWin():
    win.blit(bg,(0,0))
    q1Text= font.render(q1.q,1,(255,255,255))
    # 新增:将渲染好的文本绘制到窗口的(50,50)位置,可根据需求调整坐标
    win.blit(q1Text, (50, 50))
    pygame.display.update()
def gameLoop():
    global font
    font=pygame.font.SysFont('goudystout',15,True,False)
    global q1
    q1=question('What is the formula for speed','Time/Distance','Distance/Time','Accleration/Time','bruh')
    run= True
    while run:
        clock.tick(27)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run=False
        redrawGameWin()
gameLoop()
pygame.quit()

核心修改说明

  • 在redrawGameWin()函数中添加win.blit(q1Text, (50, 50)):这是把渲染好的文本Surface绘制到窗口的关键操作,第二个参数是文本的左上角坐标,你可以根据游戏布局自由调整位置。
  • 重温Pygame的渲染逻辑:先通过font.render()生成文本Surface对象,再用blit()将其叠加到窗口Surface上,最后调用pygame.display.update()刷新整个窗口的显示。

内容的提问来源于stack exchange,提问作者nathannotnathan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 13:02:33