【问题标题】:fail to add text on the button in pygame无法在pygame中的按钮上添加文本
【发布时间】:2018-07-12 01:46:42
【问题描述】:

我想在我的按钮上添加一个文本,我按照网上的教程并按照说明编写代码,但是文本仍然没有成功显示在按钮上,这是我的代码:

    ButtonText = pygame.font.SysFont("freesansbold.ttf", 10)
    textSurf, textRect = text_objects("Mute", ButtonText)
    textRect.center = ((20+(50/2)), (20+(20/2)))
    background.blit(textSurf, textRect)

我在顶部定义了 text_objects:

def text_objects(text, font):
    black = (0,0,0)
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()

而不是显示文本“静音”,而是在那里显示一团黑色。谁能帮我解决这个问题?先感谢您。

【问题讨论】:

  • 嗨,Wendy,你能上传完整的代码吗?
  • @SachinPatel 用户应该极少上传他们的完整代码。问题应包含minimal reproducible example。如果用户粘贴他们的完整代码,这会使问题过于具体,对其他人没有价值,而且通常包含太多代码,这使得阅读和推理变得更加困难。

标签: python button pygame


【解决方案1】:

我相信您没有为要绘制的字体指定背景,因此它会为您创建一个空白背景。也就是一个黑色的。您可能需要将代码修改为:

def text_objects(text, font):
    black = (0,0,0)
    white = (255,255,255)
    surf = pygame.Surface(font.size(text))
    surf.fill(white)
    textSurface = font.render(text, True, black, surf)
    return textSurface, textSurface.get_rect()

【讨论】:

  • 我将代码从 background.blit(textSurf, textRect) 更改为 screen.blit(textSurf, textRect)。文本现在可以显示在按钮上,但它在那里闪烁。我希望它是静态的。
  • 您需要提供更多代码。您的示例中没有屏幕参考。
【解决方案2】:

我解决了这个问题。我应该将代码background.blit(textSurf, textRect) 更改为screen.blit(textSurf, textRect)。修改后,按钮上可以显示文字,但是文字在闪烁,为了解决这个问题,我在里面加了一个时钟功能来控制更新的频率。最终代码在这里:

ButtonText = pygame.font.Font("freesansbold.ttf", 10)
textSurf, textRect = text_objects("Mute", ButtonText)
textRect.center = ((20+(50/2)), (20+(20/2)) )

screen.blit(textSurf, textRect)     
pygame.display.flip()
clock = pygame.time.Clock()
clock.tick(15)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-27
    • 1970-01-01
    相关资源
    最近更新 更多