【问题标题】:Pygame Text Line Break [duplicate]Pygame文本换行符[重复]
【发布时间】:2019-02-11 08:18:31
【问题描述】:

我正在编写使用 pygame、wikipedia 搜索程序的代码

这是我的代码的一部分

display = pygame.display.set_mode((420, 990))

sem = pygame.font.Font("fonts.ttf", 30)

def write(msg, color, x, y):
    surface = sem.render(msg, True, color)
    display.blit(surface, (x,y))

然后,我可以渲染文本。 接下来,在维基百科中输入我想获取的信息(代码跳过): 并在维基百科中获取信息(下一行) 结果 = wikipedia.summary(搜索,句子=2)

但是如果我写长句,结果是这样的: enter image description here

句子被删减了。 所以,我想要这样的结果:

上一个

Stack Overflow 是一个私有网站,fl

想要的结果

Stack Overflow 是一个私有网站, 流(句子继续)

如何在 pygame 中换行? (但我不知道句子的长度

【问题讨论】:

    标签: python text pygame


    【解决方案1】:

    这是一个运行示例(使用word_wrap 函数from the documentation):

    import pygame
    import pygame.freetype
    pygame.init()
    
    screen = pygame.display.set_mode((100, 200))
    running = True
    
    def word_wrap(surf, text, font, color=(0, 0, 0)):
        font.origin = True
        words = text.split(' ')
        width, height = surf.get_size()
        line_spacing = font.get_sized_height() + 2
        x, y = 0, line_spacing
        space = font.get_rect(' ')
        for word in words:
            bounds = font.get_rect(word)
            if x + bounds.width + bounds.x >= width:
                x, y = 0, y + line_spacing
            if x + bounds.width + bounds.x >= width:
                raise ValueError("word too wide for the surface")
            if y + bounds.height - bounds.y >= height:
                raise ValueError("text to long for the surface")
            font.render_to(surf, (x, y), None, color)
            x += bounds.width + space.width
        return x, y
    
    font = pygame.freetype.SysFont('Arial', 20)
    
    while running:
        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                running = False
        screen.fill((255, 255, 255))
        word_wrap(screen, 'Hey, this is a very long text! Maybe it is too long... We need more than one line!', font)
        pygame.display.update()
    

    结果:

    请注意这段代码如何使用pygame.freetype 模块而不是pygame.font,因为它提供了Font.render_toFont.get_rect 等很好的功能。

    【讨论】:

    • 嗯,我在 font.origin 中仍然有一个错误,“AttributeError: 'str' object has no attribute 'origin'。注意:我使用的是 python 3.6.3
    • 很抱歉,我可以再问一个问题吗?我解决了上述问题,但我仍然是一个错误。它说,AttributeError: "tuple" object has no attriubte "split" in words = text.split(" ")
    • @sloth 当我运行该示例时,ValueError: text to long for the surface 被提出。对你起作用吗?稍后我会尝试调试它。
    • @RV3000Developer 您必须将字符串作为text 参数而不是元组传递。
    • @skrx 文本被分割成单词,当单词对于表面来说太大时会发生异常。
    猜你喜欢
    • 2015-12-11
    • 2021-01-24
    • 1970-01-01
    • 2012-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2016-01-08
    相关资源
    最近更新 更多