gpt4 book ai didi

python 3 : Cannot reset colors with Colorama module

转载 作者:太空宇宙 更新时间:2023-11-04 03:25:28 25 4
gpt4 key购买 nike

我一直在尝试使用 colorama 以颜色打印字典值。

我想让用户输入选择要着色的值,并在用户选择不同的值时重置先前选择的颜色,我已经能够根据选择更改颜色是可以弄清楚如何重置之前的选择。

在下面的代码中,我重新创建了基本想法,您会在“else” block 中看到一些我尝试重置颜色的东西,但它们没有用。

我正在使用 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 字典中的内容是没有意义的,但 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 text RESET_ALL
  • GREEN GREEN a1 文本 RESET_ALL RESET_ALL
  • GREEN GREEN GREEN a1 文本 RESET_ALL RESET_ALL RESET_ALL

您需要在 else block 中移除包围 GREENRESET_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)

关于 python 3 : Cannot reset colors with Colorama module,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33199172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com