Python-Curses-Addstr-多色字符串/理解函数
我不知道该用什么词来问我的问题,所以请原谅下面的额外细节。我要求的是正确的词语/概念,而不是具体问题的答案 我试图在我的脚本前面放一个简单的控制台,使用Python中的诅咒。我希望控制台看起来比较熟悉,并且有3个命令(加载、退出、继续)的快捷键。为了突出显示哪个键是某个动作的热键,我希望该字母采用不同的颜色。(例如,ex将热键设置为x)。我认为这必须由3个“addstr”命令组成-用普通(“E”)写第一个字母,然后用颜色属性写x,然后再用普通颜色写“it” 我想,因为我做了3次,也许在未来的屏幕上会更多,我应该做一个函数,让我看看这是否有效。但我不知道如何编辑屏幕,而不将函数硬编码为变量名。我希望能够在多个不同的窗口中调用该函数。起初我以为我可以将屏幕变量传递到函数中,但这似乎不正确 这是我开始编写的伪代码:Python-Curses-Addstr-多色字符串/理解函数,python,python-2.7,curses,Python,Python 2.7,Curses,我不知道该用什么词来问我的问题,所以请原谅下面的额外细节。我要求的是正确的词语/概念,而不是具体问题的答案 我试图在我的脚本前面放一个简单的控制台,使用Python中的诅咒。我希望控制台看起来比较熟悉,并且有3个命令(加载、退出、继续)的快捷键。为了突出显示哪个键是某个动作的热键,我希望该字母采用不同的颜色。(例如,ex将热键设置为x)。我认为这必须由3个“addstr”命令组成-用普通(“E”)写第一个字母,然后用颜色属性写x,然后再用普通颜色写“it” 我想,因为我做了3次,也许在未来的屏幕
def keyString(menuString,fastChar,highlight,startX,startY,cScreen):
#menuString is the word that has a letter to bring to attention
#fastChar is the character that will be in a different colour
#highlight is binary value to determine which colour pair to use
#definition expects 'h' and 'n' to be colour pairs
#startX and startY are the beginning cursor positions
#cScreen would be global screen variable
fCidx = menuString.find(fastChar) #index of the character to highlight
fXadj = startX + fCidx #set the x position for character to highlight
sHx = fXadj + 1 #set the x position for the remainder of the string
fH = menuString[0:fCidx] #Slice the first half of the string
sH = menuString[(fCidx+1):] #slice the remainder of the string
if highlight:
txtColor = h
else:
txtColor = n
cScreen.addstr(startY,startX,fH,txtColor)
cScreen.addstr(startY,fXadj,fastChar)
cScreen.addstr(startY,sHx,sH,txtColor)
return cScreen
请忽略这些糟糕的变量名。我已经厌倦了打字,开始速记。我意识到我不需要担心显式地声明x,y坐标,因为光标位置被记住了。所以很多都可以删掉。我不是要找人来修复我的功能。我只是没有一个概念,如何有一个功能,将写出一个字,使用不同的颜色,不同的字符。我可能会在函数中粘贴一个“全局屏幕”,并仅用于编辑“屏幕”,但(例如)我将无法在“屏幕2”中使用该函数。如果这有助于将来的搜索,我发现我可以使用Windows(curses.newwin),这些窗口可以输入函数,也可以从函数返回 例如,如果上面的代码位于名为“curse_tools.py”的文件中: 这个代码可以工作。我将重新编写我的原始代码,因为在这一过程中我学到了很多东西,但也许未来的初学者会遇到这个问题,所以我想我应该发布“解决方案”。虽然我仍然不知道正确的词
这篇文章中的大部分代码来自(如果看起来很熟悉的话)如果使用
box1.getch()
而不是screen.getch()
,并且省略了screen.refresh()
和box1.refresh()
行,那么这个示例程序会更简单。
import curses
import curse_tools
def Main(screen):
curses.init_pair(1,curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(2,curses.COLOR_BLACK, curses.COLOR_GREEN)
n = curses.color_pair(1)
h = curses.color_pair(2)
curse_tools.n = n
curse_tools.h = h
try:
screen.border(0)
box1 = curses.newwin(20, 20, 5, 5)
box1.box()
box1=curse_tools.keyString("Exit","x",False,1,1,box1)
screen.refresh()
box1.refresh()
screen.getch()
finally:
curses.endwin()
curses.wrapper(Main)