如何在Python中使用pyfiglet将打印文本居中

2024-05-02 09:41:02 发布

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

我想在用py figlet(https://github.com/pwaller/pyfiglet)制作的中间文本上打印

我的代码如下所示:

from pyfiglet import Figlet

f = Figlet(font='ascii___')

def DrawText(text):
    return f.renderText(text)

print(DrawText('text')) <- Center it

在输出时,我希望使用pyfiglet打印在中心打印文本


Tags: 代码textfrompyhttps文本importgithub
2条回答

您可以将关键字justify'auto'、'left'、'center'、'right'一起使用

我这样做:

import pyfiglet

txt = "title"
banner = pyfiglet.figlet_format(txt, font="slant", justify="center")

print(banner)

我找不到一份像样的模块文档。 因此,我必须深入研究代码,找到FigletBuilder类构造函数的关键字。它是这样开始的:

class FigletBuilder(object):
    """
    Represent the internals of the build process
    """
    def __init__(self, text, font, direction, width, justify):

        self.text = list(map(ord, list(text)))
        self.direction = direction
        self.width = width
        self.font = font
        self.justify = justify

main()函数(当前第865行)中的OptionParser也给出了如何使用关键字的指示,以防您想了解有关如何使用关键字参数的更多信息,但不想滚动大约1000行代码^^^

您可以巧妙地将.center()shutil模块一起使用:

from pyfiglet import Figlet
import shutil

f = Figlet(font='ascii___')

def DrawText(text,center=True):
    if center:
      print(*[x.center(shutil.get_terminal_size().columns) for x in f.renderText(text).split("\n")],sep="\n")  
    else:
      print(f.renderText(text))

DrawText('text',center=True)

相关问题 更多 >