You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Python的str.center函数在终端窗口居中显示内容?

解决RobCO Termlink加载画面终端居中问题

问题根源

你之前的错误是因为str.center()仅接受宽度(列数)和填充字符两个参数,第二个参数不能传行数,这就是触发类型错误的原因。要实现垂直+水平居中,需要分开处理垂直方向的空行和水平方向的文本居中。


方案1:纯Python实现(无需第三方库)

利用os.get_terminal_size()获取终端尺寸,通过打印空行实现垂直居中,再用str.center()处理水平居中:

import os
import time

# 获取当前终端的行、列数
terminal_rows, terminal_cols = os.get_terminal_size()

# 定义要显示的加载内容
welcome_text = "WELCOME TO ROBCO INDUSTRIES (TM) TERMLINK"
loading_block = "▓" * 30  # 可自定义长度

# 计算垂直居中需要的前置空行:(总行数 - 内容行数) // 2
empty_lines_count = (terminal_rows - 2) // 2  # 这里内容占2行

# 打印空行实现垂直居中
print("\n" * empty_lines_count)
# 水平居中打印每一行内容
print(welcome_text.center(terminal_cols))
print(loading_block.center(terminal_cols))

# 模拟加载延迟
time.sleep(2)
# 跨平台清屏
os.system('cls' if os.name == 'nt' else 'clear')

方案2:使用curses库(更灵活,Windows兼容)

Windows下无需复杂配置,直接通过pip安装适配版本:

pip install windows-curses

curses能直接控制终端的每个坐标位置,适合动态加载场景:

import curses
import time

def render_loading(stdscr):
    # 隐藏光标
    curses.curs_set(0)
    # 获取终端尺寸
    rows, cols = stdscr.getmaxyx()

    welcome_text = "WELCOME TO ROBCO INDUSTRIES (TM) TERMLINK"
    loading_bar = "▓" * 30

    # 计算文本的居中坐标
    text_y = (rows - 2) // 2  # 垂直居中位置
    text_x = (cols - len(welcome_text)) // 2  # 水平居中位置
    bar_x = (cols - len(loading_bar)) // 2

    # 在指定坐标绘制文本
    stdscr.addstr(text_y, text_x, welcome_text)
    stdscr.addstr(text_y + 1, bar_x, loading_bar)
    stdscr.refresh()

    # 加载延迟
    time.sleep(2)
    stdscr.clear()

# curses.wrapper会自动处理终端初始化和恢复
if __name__ == "__main__":
    curses.wrapper(render_loading)

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 08:47:25