简体   繁体   English

如何使用python curses为特定字符串添加颜色?

[英]How can I add colour to a specific string using python curses?

For Example, I have string "Colour selected is red" How do I make only the word "red" red? 例如,我有字符串"Colour selected is red"如何将"Colour selected is red"如何仅使单词“ red”(红色)变为红色?

This is what I'm using to try and achieve this. 这就是我用来尝试实现这一目标的方法。

import curses

curses.start_color()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
win = curses.newwin(5 + window_height, window_width, 2, 4)

win.addstr(position + 2, 5, "Colour selected is " + "Red", curses.color_pair(1))

it's part of a bigger project so some info might be missing. 这是一个较大项目的一部分,因此可能会缺少一些信息。 But it does not work. 但这行不通。

This works: 这有效:

import curses

curses.initscr();

window_height = curses.LINES - 2
window_width = curses.COLS - 2
position = 3

curses.start_color()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
win = curses.newwin(5 + window_height, window_width, 2, 4)

win.addstr(position + 2, 5, "Colour selected is " + "Red", curses.color_pair(1))

win.getch()

If you had reduced the problem to a simple, complete program, you would probably see the problem in your original program. 如果您已将问题简化为一个简单的完整程序,则可能会在原始程序中看到该问题。

Following up on comment: in curses, the addstr function applies the attribute (including color) to the whole string parameter. 跟进注释:在curses中, addstr函数将属性(包括颜色)应用于整个字符串参数。 If you want to have different parts of the string with different attributes, you will have to make separate calls to addstr , one for each attribute as applied to parts of the original string. 如果要使字符串的不同部分具有不同的属性,则必须分别对addstr进行调用,每个调用分别应用于应用于原始字符串各部分的每个属性。 Something like this: 像这样:

win.addstr(position + 2, 5, "Colour selected is ")
win.addstr("Red", curses.color_pair(1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM