如何在Python中创建交互式文本菜单?

问题描述 投票:-3回答:3

我不知道该怎么称呼它。我想知道如何制作其中一个菜单,您可以使用箭头键突出显示您的选项,然后按Enter键接受它。

python
3个回答
3
投票

提问者承认不确定如何清楚地陈述他们所追求的东西(我知道这种感觉!)并且在问题发布后有一段时间,但鉴于他们的评论暗示他们是在文字之后,我相信像python-prompt-toolkit ,用于在许多Python项目中提供基于文本的自动完成,可以提供解决方案。

有文档here有这个使用WordCompleter的例子:

from prompt_toolkit import prompt
from prompt_toolkit.completion import WordCompleter

html_completer = WordCompleter(['<html>', '<body>', '<head>', '<title>'])
text = prompt('Enter HTML: ', completer=html_completer)
print('You said: %s' % text)

这会产生如下输出:

enter image description here

上面的示例仍然相对像仅仅在文本中呈现的ComboBox,但是有一些方法可以生成其他样式的菜单,如图库here中所示。

如果这还不够,那么另一种选择是研究包装ncurses的东西,比如https://bitbucket.org/npcole/npyscreenhttp://urwid.org/


0
投票

我认为你的意思是Combobox。这是一个基于thisPyQt的简短示例:

from PyQt4 import QtGui, QtCore
import sys

class CheckableComboBox(QtGui.QComboBox):
    def __init__(self):
        super(CheckableComboBox, self).__init__()
        self.view().pressed.connect(self.handleItemPressed)
        self.setModel(QtGui.QStandardItemModel(self))

    def handleItemPressed(self, index):
        item = self.model().itemFromIndex(index)
        if item.checkState() == QtCore.Qt.Checked:
            item.setCheckState(QtCore.Qt.Unchecked)
        else:
            item.setCheckState(QtCore.Qt.Checked)

class Dialog_01(QtGui.QMainWindow):
    def __init__(self):
        super(QtGui.QMainWindow,self).__init__()
        myQWidget = QtGui.QWidget()
        myBoxLayout = QtGui.QVBoxLayout()
        myQWidget.setLayout(myBoxLayout)
        self.setCentralWidget(myQWidget)
        self.toolbutton = QtGui.QToolButton(self)
        self.toolbutton.setText('Select Categories ')

        self.toolmenu = QtGui.QMenu(self)
        for i in range(3):
            action = self.toolmenu.addAction("Category " + str(i))
            action.setCheckable(True)
        self.toolbutton.setMenu(self.toolmenu)
        self.toolbutton.setPopupMode(QtGui.QToolButton.InstantPopup)
        myBoxLayout.addWidget(self.toolbutton)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    combo = Dialog_01()
    combo.show()
    combo.resize(480,320)
    sys.exit(app.exec_())

0
投票

你问题的答案包括你提供的例子是诅咒。该软件包非常依赖于底层操作系统。因此,如果平台独立性是关键,那么您将遇到问题。例如,有一个Windows端口UniCurses,但是如果需要,您的实现必须处理此开关。

还有一些基于curses构建的工具。四个例子Urwid。

我个人对curses有一些经验,如果你有Linux作为底层系统,如果你的要求是健壮和简单的,这将是很有趣的。喜欢你的菜单要求。我不得不说,学习曲线非常陡峭。

希望这可以帮助。但鉴于广泛的问题,这是现阶段提供的唯一细节。

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