[英]Python3: Cannot reset colors with Colorama module
我一直在嘗試使用 colorama 以顏色打印字典值。
我想讓用戶輸入選擇要着色的值並在用戶選擇不同的值時重置上一個選擇的顏色,我已經能夠根據選擇更改顏色,因為我可以弄清楚如何重置上一個選擇。
在下面的代碼中,我重新創建了基本思想,您將在“其他”塊中看到我嘗試重置顏色的一些內容,但它們不起作用。
我使用 Python 3.4 和 colorama 0.3.3
import colorama
from colorama import Fore, Back, Style
from msvcrt import getch
colorama.init()
a1 = 'a1 text'
a2 = 'a2 text'
a3 = 'a3 text'
a4 = 'a4 text'
aDict = {49: a1, 50: a2, 51: a3, 52: a4}
choice = 0
# while choice is not the letter 'q'
while choice != 113:
print('select number betweem 1 and 4:\n')
# read key
choice = ord(getch())
# loop through dict of text
for k, v in aDict.items():
# if the key is equal to the choice
if k == choice:
# set the color
aDict[k] = Fore.GREEN + v + Style.RESET_ALL
else:
# else reset the color
# aDict[k] = v + Style.RESET_ALL
# aDict[k] = Fore.RESET + v
# print(Style.RESET_ALL)
pass
# print the text
for k, v in aDict.items():
print(v)
有任何想法嗎?
回答
我能夠找到解決方案,盡管我無法在上述情況下使用它,但它在我需要的實際情況下有效。 如果不知道 allBoards dict 中的內容,它真的沒有意義,但 rowString 是重要的部分。
for boards in allBoards:
for i in range(1, 4):
for number, board in boards.items():
if number == currentBoard:
# rowString += Back.WHITE + Fore.BLACK + board[i][1] +'|'+ board[i][2] +'|'+ board[i][3] + Back.RESET + Fore.RESET + ' | '
rowString += Fore.CYAN + board[i][1] +'|'+ board[i][2] +'|'+ board[i][3] + Fore.RESET + ' | '
elif number in wins['X']:
rowString += Fore.RED + board[i][1] +'|'+ board[i][2] +'|'+ board[i][3] + Fore.RESET + ' | '
elif number in wins['O']:
rowString += Fore.GREEN + board[i][1] +'|'+ board[i][2] +'|'+ board[i][3] + Fore.RESET + ' | '
else:
rowString += board[i][1] +'|'+ board[i][2] +'|'+ board[i][3] + ' | '
rowStrings.append(rowString[:-3])
rowString = ''
i = 1
for string in rowStrings:
print(string)
if i % 3 == 0 and i != 9:
print('---------------------')
i += 1
aDict[k] = Fore.GREEN + v + Style.RESET_ALL
根據上面的行,GREEN、RESET_ALL 保持前置/附加。
GREEN
a1 文本RESET_ALL
GREEN
GREEN
a1 文本RESET_ALL
RESET_ALL
GREEN
GREEN
GREEN
a1 文本RESET_ALL
RESET_ALL
RESET_ALL
您需要刪除else
塊中的環繞GREEN
、 RESET_ALL
。
與其這樣做,不如使用簡單的if .. else ..
:
while choice != 113:
print('select number betweem 1 and 4:\n')
choice = ord(getch())
for k, v in aDict.items():
if k == choice:
print(Fore.GREEN + v + Style.RESET_ALL)
else:
print(v)
你可以試試:
print('\033[39m')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.