解決CMD命令列視窗不顯示顏色問題python

2021-09-14 06:12:54 字數 2999 閱讀 3357

最近在做乙個cmd命令列視窗顯示不同顏色的字型的功能時,發現按照網上的方法設定均不生效

1.比如最常見的方法,print("\033[0;30;40m\thello world\033[0m")

我執行的結果如下:

解決方法如下:需從colorama中匯入init

#-*- coding:utf-8 -*-

from colorama import init

init(autoreset=true)

print("\033[0;30;40m\thello world\033[0m") #黑色

print("\033[0;31;40m\thello world\033[0m") #紅色

print("\033[0;32;40m\thello world\033[0m") #綠色

print("\033[0;33;40m\thello world\033[0m") #黃色

print("\033[0;34;40m\thello world\033[0m") #藍色

print("\033[0;35;40m\thello world\033[0m") #紫色

print("\033[0;36;40m\thello world\033[0m") #淺藍

print("\033[0;37;40m\thello world\033[0m") #白色

執行結果:

2.方法二,使用fore設定顏色

from colorama import init,fore

init(autoreset=true)

print (fore.yellow + "welcome to python !!")

print ("automatically back to default color again")

print(fore.red+'score: ' + str(100))

執行結果:

3.方法三,使用init_pair,color_pair設定顏色

import curses

stdscr=curses.initscr()

def display_info1(str,x,y,colorpair=1):#x,y是橫縱座標

#使用指定的colorpair顯示文字

stdscr.addstr(y,x,str,curses.color_pair(colorpair))

stdscr.refresh()

def display_info2(str,x,y,colorpair=2):#x,y是橫縱座標

#使用指定的colorpair顯示文字

stdscr.addstr(y,x,str,curses.color_pair(colorpair))

stdscr.refresh()

def get_ch_and_continue():

#演示press any key to continue

#設定nodelay為0時變成阻塞式等待

stdscr.nodelay(0)

#輸入乙個字元

ch=stdscr.getch()

#重置nodelay,使得控制台可以以非阻塞的方式接受控制台輸入,超時1秒

stdscr.nodelay(1)

return true

def set_win():

#控制台設定

global stdscr

#使用顏色首先需要呼叫這個方法

curses.start_color()

#文字和背景色設定,設定了兩個color pair,分別為1和2

curses.init_pair(1,curses.color_green,curses.color_black)

curses.init_pair(2,curses.color_red,curses.color_black)

#關閉螢幕回顯

curses.noecho()

#輸入時不需要回車確認

curses.cbreak()

#設定nodelay,使得控制台可以以非阻塞的方式接受控制台輸入,超時1秒

stdscr.nodelay(1)

def unset_win():

#恢復控制台預設設定(若不恢復,會導致即使程式結束退出了,控制台仍然是沒有回顯的)

curses.nocbreak()

stdscr.keypad(0)

curses.echo()

#結束視窗

curses.endwin()

if __name__=='__main__':

try:

set_win()

display_info1('hello,curses!',5,5)

display_info2('press any key to continue...',0,10)

get_ch_and_continue()

except exception as e:

raise e

finally:

unset_win()

執行結果:

另附:python**實現2048-功能拓展在控制台輸出顏色的例項。

cmd命令列視窗顯示中文亂碼

cmd命令列視窗顯示中文亂碼,多是因為cmd命令列視窗字元編碼不匹配導致。修改cmd視窗字元編碼為utf 8,命令列中執行 chcp 65001 切換回中文 chcp 936 這兩條命令只在當前視窗生效,重啟後恢復之前的編碼。切換cmd視窗字元編碼有風險,例如切換過以後中文顯示亂碼,並且不能永久切換...

修改cmd命令列視窗顏色的方法

修改cmd命令列視窗顏色的方法 這是乙個修改cmd命令列視窗顏色的方法。首先,新建乙個.cmd檔案,檔名可以自定,例如cmd.cmd,在裡面輸入以下三行內容 echo off color 80 echo on 其中,color 3c 則是設定cmd視窗的前景和背景顏色,前乙個數字或字母為背景色,後乙...

python 控制 cmd 命令列顏色

基於win7 python3.4 windows cmd命令列顏色 控制代碼號std input handle 10std output handle 11std error handle 12 前景色 foreground black 0x0 黑foreground blue 0x01 藍fore...