本文目录导读:
我来为你提供几个Python控制台美化的案例,从简单到复杂:
基础颜色美化(使用colorama)
from colorama import init, Fore, Back, Style
import time
# 初始化colorama(Windows支持)
init(autoreset=True)
def basic_colors():
"""基础颜色示例"""
print(Fore.RED + "红色文字")
print(Fore.GREEN + "绿色文字")
print(Fore.BLUE + "蓝色文字")
print(Fore.YELLOW + "黄色文字")
print(Fore.MAGENTA + "紫色文字")
print(Fore.CYAN + "青色文字")
# 背景色
print(Back.YELLOW + Fore.BLACK + "黄底黑字")
print(Back.GREEN + Fore.WHITE + "绿底白字")
# 样式
print(Style.BRIGHT + "加粗文字")
print(Style.DIM + "暗淡文字")
print(Style.NORMAL + "正常文字")
# 运行
basic_colors()
渐变文字效果
import sys
import time
from colorama import Fore, Style, init
init()
def gradient_text(text, colors):
"""渐变色文字效果"""
result = ""
for i, char in enumerate(text):
color = colors[i % len(colors)]
result += color + char
return result + Style.RESET_ALL
def gradient_effect():
"""动态渐变效果"""
text = "Python控制台美化"
colors_list = [
[Fore.RED, Fore.YELLOW, Fore.GREEN, Fore.CYAN, Fore.BLUE, Fore.MAGENTA],
[Fore.MAGENTA, Fore.CYAN, Fore.GREEN, Fore.YELLOW, Fore.RED],
]
for colors in colors_list:
print(gradient_text(text, colors))
time.sleep(1)
gradient_effect()
进度条美化
import time
from colorama import Fore, Style, init
init()
class ProgressBar:
"""美化进度条"""
def __init__(self, total, width=50, fill_char='█', empty_char='░'):
self.total = total
self.width = width
self.fill_char = fill_char
self.empty_char = empty_char
def update(self, current, text="处理中"):
percent = (current / self.total) * 100
filled = int(self.width * current // self.total)
bar = self.fill_char * filled + self.empty_char * (self.width - filled)
# 颜色根据进度变化
if percent < 33:
color = Fore.RED
elif percent < 66:
color = Fore.YELLOW
else:
color = Fore.GREEN
print(f"\r{color}{text}: |{bar}| {percent:.1f}% {Style.RESET_ALL}", end='')
if current >= self.total:
print(f"\n{Fore.GREEN}✓ 完成!{Style.RESET_ALL}")
# 使用示例
def demo_progress():
total = 50
pb = ProgressBar(total, width=40)
print(f"{Fore.CYAN}任务开始...{Style.RESET_ALL}\n")
for i in range(1, total + 1):
pb.update(i)
time.sleep(0.1)
demo_progress()
表格美化
from colorama import Fore, Back, Style, init
import random
init()
def create_table():
"""美化的表格"""
headers = ["序号", "姓名", "年龄", "城市", "得分"]
data = [
[1, "张三", 25, "北京", 95],
[2, "李四", 30, "上海", 88],
[3, "王五", 28, "广州", 92],
[4, "赵六", 35, "深圳", 87],
]
# 计算列宽
col_widths = [max(len(str(item)) for item in col) + 2 for col in zip(headers, *data)]
def print_separator():
"""打印分隔线"""
print(Fore.CYAN + "+" + "+".join("-" * w for w in col_widths) + "+" + Style.RESET_ALL)
def print_row(row, color=Fore.WHITE):
"""打印行"""
print(color + "|" + "|".join(f" {str(item).center(w-2)} " for item, w in zip(row, col_widths)) + "|" + Style.RESET_ALL)
# 打印表头
print_separator()
print_row(headers, Fore.YELLOW + Style.BRIGHT)
print_separator()
# 打印数据
for i, row in enumerate(data):
if i % 2 == 0:
print_row(row, Fore.WHITE)
else:
print_row(row, Fore.CYAN)
print_separator()
create_table()
动画特效
import time
import sys
from colorama import Fore, Style, init
init()
class Animation:
"""控制台动画效果"""
@staticmethod
def loading_spinner(text="加载中"):
"""加载旋转动画"""
spinner = ['|', '/', '-', '\\']
for i in range(20):
for char in spinner:
sys.stdout.write(f"\r{Fore.CYAN}{text} {char}{Style.RESET_ALL}")
sys.stdout.flush()
time.sleep(0.1)
print(f"\r{Fore.GREEN}✓ 完成!{Style.RESET_ALL} ")
@staticmethod
def typing_effect(text, delay=0.05):
"""打字机效果"""
for char in text:
sys.stdout.write(Fore.GREEN + char + Style.RESET_ALL)
sys.stdout.flush()
time.sleep(delay)
print()
@staticmethod
def rainbow_text(text):
"""彩虹文字效果"""
colors = [Fore.RED, Fore.YELLOW, Fore.GREEN, Fore.CYAN, Fore.BLUE, Fore.MAGENTA]
for i, char in enumerate(text):
print(colors[i % len(colors)] + char, end='', flush=True)
time.sleep(0.05)
print(Style.RESET_ALL)
# 使用示例
def demo_animations():
Animation.loading_spinner()
Animation.typing_effect("这是打字机效果的文字...", 0.1)
Animation.rainbow_text("🌈 彩虹文字效果")
demo_animations()
综合案例:美化菜单系统
from colorama import Fore, Back, Style, init
import time
import os
init()
class MenuSystem:
"""美化的菜单系统"""
def __init__(self):
self.options = {
"1": ("开始游戏", self.start_game),
"2": ("设置", self.settings),
"3": ("quot;, self.about),
"0": ("退出", self.exit_app)
}
def clear_screen(self):
"""清屏"""
os.system('cls' if os.name == 'nt' else 'clear')
def show_banner(self):
"""显示横幅"""
banner = """
╔═══════════════════════════════════╗
║ 🎮 Python控制台美化演示 ║
║ ╔══╗╔══╗╔╗──╔══╗╔══╗╔═╗╔═╗ ║
║ ╚╗╔╝║╔╗║║║──║╔═╝║╔╗║║║╚╝║║ ║
║ ─║║─║║║║║║──║║──║║║║║╔╗─║║ ║
║ ─║║─║║║║║║──║║──║║║║║║╚╗║║ ║
║ ╔╝╚╗║╚╝║║╚═╗║╚═╗║╚╝║║║─║║║ ║
║ ╚══╝╚══╝╚══╝╚══╝╚══╝╚╝─╚╝║ ║
╚═══════════════════════════════════╝
"""
print(Fore.CYAN + Style.BRIGHT + banner + Style.RESET_ALL)
def show_menu(self):
"""显示菜单"""
self.clear_screen()
self.show_banner()
print(f"\n{Fore.YELLOW}{'='*50}{Style.RESET_ALL}")
print(f"{Fore.GREEN}请选择操作:{Style.RESET_ALL}")
print(f"{Fore.YELLOW}{'='*50}{Style.RESET_ALL}\n")
for key, (name, _) in self.options.items():
if key == "0":
print(f" {Fore.RED}[{key}] {name}{Style.RESET_ALL}")
else:
print(f" {Fore.CYAN}[{key}] {name}{Style.RESET_ALL}")
print(f"\n{Fore.YELLOW}{'='*50}{Style.RESET_ALL}")
def start_game(self):
print(f"\n{Fore.GREEN}🎮 游戏开始!{Style.RESET_ALL}")
time.sleep(2)
def settings(self):
print(f"\n{Fore.BLUE}⚙️ 设置界面{Style.RESET_ALL}")
time.sleep(2)
def about(self):
print(f"\n{Fore.MAGENTA}📝 控制台美化演示程序 v1.0{Style.RESET_ALL}")
time.sleep(2)
def exit_app(self):
print(f"\n{Fore.RED}👋 退出程序...{Style.RESET_ALL}")
time.sleep(1)
return False
def run(self):
while True:
self.show_menu()
choice = input(f"\n{Fore.YELLOW}请输入选项: {Style.RESET_ALL}")
if choice in self.options:
self.clear_screen()
result = self.options[choice][1]()
if result == False:
break
else:
print(f"{Fore.RED}❌ 无效选项!{Style.RESET_ALL}")
time.sleep(1)
# 运行菜单系统
if __name__ == "__main__":
menu = MenuSystem()
menu.run()
安装依赖
pip install colorama
使用建议
- 保持一致性:在一个项目中统一使用相同的美化风格
- 适度美化:不要过度使用颜色和特效,以免影响可读性
- 考虑兼容性:Windows可能需要额外配置,使用colorama解决
- 关注性能:动画效果要注意延迟时间,避免卡顿
这些案例涵盖了控制台美化的主要场景,你可以根据实际需求选择和组合使用。
标签: 日志高亮