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

使用Pygame的drawText函数绘制多文本后,如何获取指定文本位置?

解决Pygame中获取已绘制文本位置的问题

我是Python和Pygame新手,使用以下自定义函数绘制文本后,希望获取之前绘制的文本“YES”的位置,请问该如何实现?

自定义函数及调用代码:

def drawText(text, x, y, colour):
   font = pygame.font.SysFont('Arial', 30)
   textSurface = font.render(text, True, colour)
   textRect = textSurface.get_rect()
   textRect.center = (x, y)
   screen.blit(textSurface, textRect)

drawText("YES", 120, 300, GREEN)  

核心思路

原函数仅完成绘制操作,未保存文本的位置信息(textRect对象)。要获取位置,关键是保存绘制时生成的textRect,以下是几种实用方案:


方法1:修改drawText函数,返回文本的Rect对象

让函数返回绘制时的textRect,调用时将其保存到变量中,后续可随时获取位置:

def drawText(text, x, y, colour):
    font = pygame.font.SysFont('Arial', 30)
    textSurface = font.render(text, True, colour)
    textRect = textSurface.get_rect()
    textRect.center = (x, y)
    screen.blit(textSurface, textRect)
    return textRect  # 返回Rect对象

# 调用时保存返回的Rect
yes_rect = drawText("YES", 120, 300, GREEN)

# 后续获取位置信息
print("YES的中心坐标:", yes_rect.center)
print("YES的左上角坐标:", yes_rect.topleft)
print("YES的矩形区域范围:", yes_rect)

方法2:用容器存储所有文本信息(适合多文本场景)

如果需要管理多个绘制的文本,可用字典或列表存储每个文本的内容与对应Rect,方便后续查询:

# 初始化字典存储文本记录
text_records = {}

def drawText(text, x, y, colour):
    font = pygame.font.SysFont('Arial', 30)
    textSurface = font.render(text, True, colour)
    textRect = textSurface.get_rect()
    textRect.center = (x, y)
    screen.blit(textSurface, textRect)
    # 将文本和对应Rect存入字典
    text_records[text] = textRect

# 绘制多个文本
drawText("YES", 120, 300, GREEN)
drawText("HELLO", 200, 400, RED)

# 获取"YES"的位置
if "YES" in text_records:
    yes_rect = text_records["YES"]
    print("YES的中心坐标:", yes_rect.center)

方法3:重新计算文本Rect(不推荐,冗余操作)

如果不想修改原函数,可重新生成一次文本的Surface和Rect,但会重复执行渲染操作,效率较低:

# 重新计算"YES"的Rect(需和绘制时参数一致)
font = pygame.font.SysFont('Arial', 30)
yes_surface = font.render("YES", True, GREEN)
yes_rect = yes_surface.get_rect()
yes_rect.center = (120, 300)

# 获取位置信息
print("YES的中心坐标:", yes_rect.center)

补充说明

  • Rect对象包含丰富的位置属性:center(中心坐标)、topleft(左上角)、bottomright(右下角)、x/y(左上角x/y值)等,可按需调用。
  • 优先选择方法1或方法2,避免冗余计算,代码更简洁高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 10:20:43