在Python终端中显示简单图形

在Python终端中显示简单图形,虽然不如图形界面库强大,但可以通过以下几种方法实现:

方法1:使用ASCII字符绘制基本形状

# 绘制矩形
def draw_rectangle(width, height):
    for h in range(height):
        if h == 0 or h == height-1:
            print('*' * width)
        else:
            print('*' + ' ' * (width-2) + '*')

# 绘制三角形
def draw_triangle(size):
    for i in range(1, size+1):
        print(' ' * (size-i) + '*' * (2*i-1))

# 使用示例
draw_rectangle(10, 5)
print("\n")
draw_triangle(5)

方法2:使用ANSI转义码绘制彩色图形

# 彩色方块(支持大多数现代终端)
def draw_color_block(width, height, color_code=41):  # 41=红色背景
    for _ in range(height):
        print(f"\033[{color_code}m{' ' * width}\033[0m")

# 使用示例
draw_color_block(20, 5)  # 红色方块
draw_color_block(15, 3, 44)  # 蓝色方块(44=蓝)

方法3:使用curses库(Unix/Linux/macOS)

import curses

def main(stdscr):
    stdscr.clear()
    # 绘制边框
    stdscr.border()
    # 绘制线条
    stdscr.addstr(2, 2, "Hello Terminal Graphics!")
    # 绘制矩形
    for y in range(5, 10):
        stdscr.addch(y, 5, '|')
        stdscr.addch(y, 20, '|')
    # 刷新显示
    stdscr.refresh()
    stdscr.getch()

curses.wrapper(main)

方法4:使用termplotlib库(需要安装)

pip install termplotlib
import termplotlib as tpl
import numpy as np

# 创建正弦曲线数据
x = np.linspace(0, 2*np.pi, 20)
y = np.sin(x)

# 在终端绘图
fig = tpl.figure()
fig.plot(x, y, label="sin(x)", width=50, height=15)
fig.show()

方法5:使用blessed库绘制交互图形

pip install blessed
from blessed import Terminal

term = Terminal()
print(term.clear)

# 绘制彩色矩形
with term.location(10, 5):
    print(term.on_red + ' ' * 20)

for y in range(6, 10):
    with term.location(10, y):
        print(term.on_red + ' ' + term.on_blue + ' ' * 18 + term.on_red + ' ')

with term.location(10, 10):
    print(term.on_red + ' ' * 20 + term.normal)

各方法特点对比:

方法 复杂度 跨平台 交互性 依赖库
ASCII字符 ★☆☆☆☆
ANSI转义码 ★★☆☆☆ 部分支持
curses ★★★★☆ Linux/mac 标准库(curses)
termplotlib ★★★☆☆ 需安装
blessed ★★★★☆ 需安装

注意事项:

  1. ANSI转义码在Windows CMD中需要启用VT100支持(Win10+默认支持)
  2. 对于更复杂的图形,建议使用图形界面库(matplotlib, Pygame等)
  3. 使用前确保终端支持Unicode字符和ANSI颜色

这些方法可以在不离开终端环境的情况下,实现基本的图形展示功能。

posted @ 2025-06-25 10:48  nxhujiee  阅读(26)  评论(0)    收藏  举报