Simple way to display text on screen in Python?

后端 未结 2 1550
再見小時候
再見小時候 2020-12-16 08:55

I\'ve been googling and looking through StackOverflow but no luck...

What I would like is to display text to the screen (not console) for an art project I am develop

2条回答
  •  清酒与你
    2020-12-16 09:21

    Here's a pygame solution. Just pass the random letters and color to Font.render and then blit the returned surface. To center it I call the get_rect method of the txt surface and pass the center of the screen_rect as the center argument. Note that you can't choose a different color for each letter. To do that you would probably have to render several "one letter" surfaces and then combine them.

    Epilepsy warning - The text was getting changed really quickly (each frame (30 fps)) and I wasn't sure if that could cause epileptic seizures, so I added a timer to update the text only every 10 frames. Be careful if you want to increase the update speed.

    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()
    

提交回复
热议问题