python在cmd窗口显示彩色文字

新手小白,一直在为cmd窗口的暗白色文字感到苦恼,在网上找了许多方法(也就那两种),现在稍微整理了一下,便于使用。

效果图:

python在cmd窗口显示彩色文字_第1张图片

import ctypes
  
STD_INPUT_HANDLE = -10  
STD_OUTPUT_HANDLE= -11  
STD_ERROR_HANDLE = -12  
  
FOREGROUND_DARKBLUE = 0x01 # 暗蓝色
FOREGROUND_DARKGREEN = 0x02 # 暗绿色
FOREGROUND_DARKSKYBLUE = 0x03 # 暗天蓝色
FOREGROUND_DARKRED = 0x04 # 暗红色
FOREGROUND_DARKPINK = 0x05 # 暗粉红色
FOREGROUND_DARKYELLOW = 0x06 # 暗黄色
FOREGROUND_DARKWHITE = 0x07 # 暗白色
FOREGROUND_DARKGRAY = 0x08 # 暗灰色
FOREGROUND_BLUE = 0x09 # 蓝色
FOREGROUND_GREEN = 0x0a # 绿色
FOREGROUND_SKYBLUE = 0x0b # 天蓝色
FOREGROUND_RED = 0x0c # 红色
FOREGROUND_PINK = 0x0d # 粉红色
FOREGROUND_YELLOW = 0x0e # 黄色
FOREGROUND_WHITE = 0x0f # 白色

std_out_handle=ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)

def set_cmd_text_color(color, handle=std_out_handle):
    Bool=ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color)
    return Bool

def resetColor():
    set_cmd_text_color(FOREGROUND_DARKWHITE)

def cprint(mess,color):
    if color=='暗蓝色':
        set_cmd_text_color(FOREGROUND_DARKBLUE)

    elif color=='暗绿色':
        set_cmd_text_color(FOREGROUND_DARKGREEN)

    elif color=='暗天蓝色':
        set_cmd_text_color(FOREGROUND_DARKSKYBLUE)
        
    elif color=='暗红色':
        set_cmd_text_color(FOREGROUND_DARKRED)

    elif color=='暗粉红色':
        set_cmd_text_color(FOREGROUND_DARKPINK)
        
    elif color=='暗黄色':
        set_cmd_text_color(FOREGROUND_DARKYELLOW)

    elif color=='暗白色':
        set_cmd_text_color(FOREGROUND_DARKWHITE)

    elif color=='暗灰色':
        set_cmd_text_color(FOREGROUND_DARKGRAY)

    elif color=='蓝色':
        set_cmd_text_color(FOREGROUND_BLUE)

    elif color=='绿色':
        set_cmd_text_color(FOREGROUND_GREEN)

    elif color=='天蓝色':
        set_cmd_text_color(FOREGROUND_SKYBLUE)

    elif color=='红色':
        set_cmd_text_color(FOREGROUND_RED)

    elif color=='粉红色':
        set_cmd_text_color(FOREGROUND_PINK)

    elif color=='黄色':
        set_cmd_text_color(FOREGROUND_YELLOW)

    elif color=='白色':
        set_cmd_text_color(FOREGROUND_WHITE)
        
    print(mess)
    resetColor()

if __name__=='__main__':
    while 1:
        mess=input('信息:')
        color=input('颜色:')
        cprint(mess,color)
使用方法:

from cmdFontColor import *

cprint('信息','颜色')

你可能感兴趣的:(python)