首页 > 解决方案 > 打印时更改文本颜色

问题描述

我目前正在设计一个简单的游戏,并且正在尝试更改正在打印的特定事物的颜色。我已经下载了 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='tartley@tartley.com',
    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

标签: pythonpython-3.xpython-3.8colorama

解决方案


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

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

推荐阅读