AFAIK,Python 中还没有可用的 curses 菜单扩展,所以你必须推出自己的解决方案。我知道这个补丁http://bugs.python.org/issue1723038但我不知道它的当前状态是什么。我找到了一个不错的 Python 类,它在这里http://www.promisc.org/blog/?p=33包装了我想要的“cmenu”,但我也有这个问题。我想制作一个菜单,用户可以在其中选择突出显示的元素,但我不想立即执行特定操作,而是想显示另一个菜单,然后可能是另一个,要求输入等。我的第一个想法是删除现有的 cmenu screen.clear() 或 cleanup() 但在绘制新菜单之前不会删除旧菜单,新菜单如下所示:
0. top
1. Exit
2. Another menu
-- end of the old menu that should go away --
3. first
4. second
5. third
cmenu() 中没有用于删除项目的 remove() 方法。我猜旧菜单未清除的事实是由 display() 方法中的“while True”循环引起的,但是当我删除它时,发生了一些奇怪的事情。我正在使用 Python 2.7,这是我当前的代码:
#!/usr/bin/python
#
# Adapted from:
# http://blog.skeltonnetworks.com/2010/03/python-curses-custom-menu/
#
# Goncalo Gomes
# http://promisc.org
#
import signal
signal.signal(signal.SIGINT, signal.SIG_IGN)
import os
import sys
import curses
import traceback
import atexit
import time
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
class cmenu(object):
datum = {}
ordered = []
pos = 0
def __init__(self, options, title="python curses menu"):
curses.initscr()
curses.start_color()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)
curses.curs_set(0)
self.screen = curses.initscr()
self.screen.keypad(1)
self.h = curses.color_pair(1)
self.n = curses.A_NORMAL
for item in options:
k, v = item.items()[0]
self.datum[k] = v
self.ordered.append(k)
self.title = title
atexit.register(self.cleanup)
def cleanup(self):
curses.doupdate()
curses.endwin()
def upKey(self):
if self.pos == (len(self.ordered) - 1):
self.pos = 0
else:
self.pos += 1
def downKey(self):
if self.pos <= 0:
self.pos = len(self.ordered) - 1
else:
self.pos -= 1
def display(self):
screen = self.screen
while True:
screen.clear()
screen.addstr(2, 2, self.title, curses.A_STANDOUT|curses.A_BOLD)
screen.addstr(4, 2, "Please select an interface...", curses.A_BOLD)
ckey = None
func = None
while ckey != ord('\n'):
for n in range(0, len(self.ordered)):
optn = self.ordered[n]
if n != self.pos:
screen.addstr(5 + n, 4, "%d. %s" % (n, optn), self.n)
else:
screen.addstr(5 + n, 4, "%d. %s" % (n, optn), self.h)
screen.refresh()
ckey = screen.getch()
if ckey == 258:
self.upKey()
if ckey == 259:
self.downKey()
ckey = 0
self.cleanup()
if self.pos >= 0 and self.pos < len(self.ordered):
self.datum[self.ordered[self.pos]]()
self.pos = -1
else:
curses.flash()
def top():
os.system("top")
def exit():
sys.exit(1)
def submenu():
# c.screen.clear() # nope
# c.cleanup() # nope
submenu_list = [{"first": exit}, {"second": exit}, {"third": exit}]
submenu = cmenu(submenu_list)
submenu.display()
try:
list = [{ "top": top }, {"Exit": exit}, {"Another menu": submenu}]
c = cmenu(list)
c.display()
except SystemExit:
pass
else:
#log(traceback.format_exc())
c.cleanup()