打印时更改文本的颜色

问题描述 投票:0回答:2

我目前正在设计一个简单的游戏,我正在尝试更改要打印的特定内容的颜色。我已经下载了colorama模块,并使用在网上找到的示例运行了我的代码,但这是行不通的(稍后再详细介绍)。我知道Python选项中的设置,但这会影响整个文本而不是特定的部分。如果这有助于我的计算机运行Windows,而我正在运行Python 3.8。这是安装代码,然后是我在另一个文件中包含的代码的几行。在此之后的几行是输出:

from setuptools import setup, find_packages

name = 'colorama'
version = '0.1'

def get_long_description(filename):
    readme = join(dirname(__file__), filename)
    return open(readme).read()


setup(
    name=name,
    version=version,
    description="Cross-platform colored terminal text.",
    long_description=get_long_description('README.txt'),
    keywords='color colour terminal text ansi windows crossplatform xplatform',
    author='Jonathan Hartley',
    author_email='[email protected]',
    url='http://code.google.com/p/colorama/',
    license='BSD',
    packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
    include_package_data=True,
    zip_safe=True,
    install_requires=[
      # -*- Extra requirements: -*-
    ],
    entry_points="""
# -*- Entry points: -*-
    """,
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2.6',
        'Topic :: Terminals',
    ]
    # see classifiers http://pypi.python.org/pypi?%3Aaction=list_classifiers
)



import colorama
from colorama import Fore, Style
print(Fore.BLUE + "Hello World")



[34mHello World
python python-3.x python-3.8 colorama
2个回答
0
投票

文档指出您需要通过调用init()函数开始

应用程序应使用以下方式初始化Colorama:

   from colorama import init 
   init()

具有以下效果

在Windows上,调用init()将从所有发送到stdout或stderr的文本中筛选出ANSI转义序列,并将其替换为等效的Win32调用。

这正是您所看到的,因为您一开始就看到[34m


0
投票

您需要在导入colorama之后且在打印带有颜色的字符串之前在某个地方调用init()。例如:

import colorama
from colorama import Fore, Style
init()
print(Fore.BLUE + "Hello World")

希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.