您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Python中在屏幕上显示文本的简单方法?

在Python中在屏幕上显示文本的简单方法?

这是一个pygame解决方案。只需将随机字母和颜色传递给Font.render,然后将返回的表面变白。为了使它居中,我调用了曲面的get_rect方法并将参数txt的中心screen_rect作为center参数传递。请注意,您不能为每个字母选择不同的颜色。为此,您可能必须渲染几个“一个字母”的曲面,然后将它们组合起来。

-文本变化非常快(每帧(30 fps)),我不确定是否会引起癫痫发作,因此我添加一个计时器,每10帧才更新一次文本。如果要提高更新速度,请小心。

import sys
from random import choice, randrange
from string import ascii_letters

import pygame as pg


def random_letters(n):
    """Pick n random letters."""
    return ''.join(choice(ascii_letters) for _ in range(n))


def main():
    info = pg.display.Info()
    screen = pg.display.set_mode((info.current_w, info.current_h), pg.FULLSCREEN)
    screen_rect = screen.get_rect()
    font = pg.font.Font(None, 45)
    clock = pg.time.Clock()
    color = (randrange(256), randrange(256), randrange(256))
    txt = font.render(random_letters(randrange(5, 21)), True, color)
    timer = 10
    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_ESCAPE:
                    done = True

        timer -= 1
        # Update the text surface and color every 10 frames.
        if timer <= 0:
            timer = 10
            color = (randrange(256), randrange(256), randrange(256))
            txt = font.render(random_letters(randrange(5, 21)), True, color)

        screen.fill((30, 30, 30))
        screen.blit(txt, txt.get_rect(center=screen_rect.center))

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
    sys.exit()
python 2022/1/1 18:29:55 有491人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶