You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

求可生成字符画基础形状的轻量Python库(替代turtle/tkinter)

推荐轻量级Python工具生成基础字符画形状

完全明白你的需求——不需要turtle、tkinter那种带GUI或者复杂绘图能力的库,就想要个简单直接能生成类似你给出的边框、带分区的字符画基础形状的工具对吧?这里有几个不错的选择:

1. Rich(最推荐)

Rich是一个超级易用的终端美化库,其中的Panel组件可以快速生成各种样式的字符画边框,而且支持自定义内容、分割布局,代码非常简洁。

示例代码:

生成你给出的空框:

from rich.panel import Panel
from rich import print

print(Panel("", width=9, box=rich.box.SQUARE))

生成带内部分区的框(类似你第一个例子的布局):

from rich.panel import Panel
from rich.table import Table
from rich import print

# 创建一个2x2的表格,用来模拟分区
table = Table(show_header=False, box=None, padding=(1, 2))
table.add_row("1 2", "3 4")
# 把表格放到Panel里
print(Panel(table, width=9, box=rich.box.SQUARE))

Rich的边框样式还可以自定义,比如用box=rich.box.ROUNDED换成圆角边框,完全满足基础形状的需求,而且代码量极少。

2. 自己封装轻量函数(零依赖)

如果连第三方库都不想装,其实可以自己写个简单的函数来生成这类基础框,因为需求本身很简单。比如下面这个生成带可选内部分割的框的函数:

def draw_box(width, height, split_horizontal=False, split_vertical=False, 
             top_left="|", top_right="|", bottom_left="|", bottom_right="|", 
             horizontal="-", vertical="|"):
    # 顶部边框
    print(f"{top_left}{horizontal*(width-2)}{top_right}")
    # 中间行
    for i in range(height-2):
        if split_horizontal and i == (height-2)//2:
            # 水平分割线
            print(f"{vertical}{horizontal*(width-2)}{vertical}")
        else:
            line = vertical
            if split_vertical:
                line += " "*(width//2 -1) + vertical + " "*(width//2 -1)
            else:
                line += " "*(width-2)
            line += vertical
            print(line)
    # 底部边框
    print(f"{bottom_left}{horizontal*(width-2)}{bottom_right}")

# 调用生成你第一个例子的框
draw_box(9,5, split_horizontal=True, split_vertical=True, 
         top_left="|", top_right="|", bottom_left="|", bottom_right="|", 
         horizontal="-", vertical="|")
# 调用生成空框
draw_box(9,5, top_left="|", top_right="|", bottom_left="|", bottom_right="|", 
         horizontal="-", vertical="|")

这个函数完全零依赖,你可以根据自己的需求调整边框字符、是否添加分割线,灵活性拉满。

3. Asciimatics

如果你需要更多一点的字符画形状(比如圆形、三角形),Asciimatics是个不错的轻量库,它专门处理终端字符画,API也很直观,不过比Rich稍微重一点,但依然比turtle之类的简洁很多。

示例代码(生成矩形框):

from asciimatics.screen import Screen
from asciimatics.shapes import Rectangle

def demo(screen):
    rect = Rectangle(screen, 0, 0, 8, 4, colour=7)
    rect.draw()
    screen.refresh()
    screen.wait_for_input()

Screen.wrapper(demo)

这个库还支持绘制其他基础几何形状,适合需要更多形状类型的场景。


内容的提问来源于stack exchange,提问作者Sadaf Shafi

火山引擎 最新活动