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

2024-06-06 10:05:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在google上搜索StackOverflow,但是没有运气。。。

我想为我正在开发的一个艺术项目在屏幕上显示文本(不是控制台)。字符串将以全屏显示——无需菜单栏的边到边“窗口”等。字符串将快速更新(想象一个随机字母字符串显示和重新绘制的速度将尽可能快)。字体和颜色的选择(一个字母一个字母的基础上)将是巨大的奖金。

字符串将在屏幕上居中(不滚动)。

我是编程新手。在屏幕上显示文本似乎比我想象的要复杂得多。:)

我遇到过使用pygame的解决方案,但是示例代码不起作用。下面是一个典型的例子:

https://www.daniweb.com/programming/software-development/code/244474/pygame-text-python

我在Mac电脑上看到的是一个窗口,没有文本,代码无限期地继续运行。我遇到的其他代码和其他库的类似经验。

pygame是我的最佳选择(易于用Python编程、高速)还是有其他更适合我所追求的库?

如果pygame是正确的方向,有人能推荐一些示例代码来帮助我吗?

谢谢

——达林


Tags: 项目字符串代码文本示例屏幕编程google
2条回答

使用Tkinter可以很容易地完成这类工作,Tkinter包含在大多数现代Python安装中。例如

import tkinter as tk
from random import seed, choice
from string import ascii_letters

seed(42)

colors = ('red', 'yellow', 'green', 'cyan', 'blue', 'magenta')
def do_stuff():
    s = ''.join([choice(ascii_letters) for i in range(10)])
    color = choice(colors)
    l.config(text=s, fg=color)
    root.after(100, do_stuff)

root = tk.Tk()
root.wm_overrideredirect(True)
root.geometry("{0}x{1}+0+0".format(root.winfo_screenwidth(), root.winfo_screenheight()))
root.bind("<Button-1>", lambda evt: root.destroy())

l = tk.Label(text='', font=("Helvetica", 60))
l.pack(expand=True)

do_stuff()
root.mainloop()

用鼠标左键单击退出。

这只是概念的证明。要逐个字母地控制颜色和/或字体,您需要做一些更复杂的事情。可以使用一行标签小部件(每个字母一个),也可以使用文本小部件。


但是,如果在Mac上尝试此操作,则窗口可能无法接收焦点,如here所述。答案here显示了获得全屏窗口的另一种方法,但我怀疑它可能也有同样的缺陷。

root.attributes("-fullscreen", True)

这种方法的一个优点是不需要root.geometry调用。

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

癫痫警告-文本变化非常快(每帧30帧),我不确定这是否会导致癫痫发作,所以我添加了一个计时器,每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()

相关问题 更多 >