Add support for cursorless menus

When a highlighter is used instead of a cursor it looks much better when
all the options have the same length. With right_pad_options all options
are right-padded with spaces so they have the same length. Also, an
example for a cursorless menu is added.
This commit is contained in:
Sebastian Lohff 2020-09-06 21:08:06 +02:00
parent 7a09d45ab8
commit 775c50ed6f
2 changed files with 18 additions and 1 deletions

View File

@ -93,7 +93,7 @@ class CliMenu:
def __init__(self, options=None, header=None, cursor=None, style=None,
indent=2, dedent_selection=False, initial_pos=0,
option_prefix=' ', option_suffix=''):
option_prefix=' ', option_suffix='', right_pad_options=False):
self._items = []
self._item_num = 0
self._ran = False
@ -105,6 +105,7 @@ class CliMenu:
self._option_indent = indent
self._header_indent = indent
self._dedent_selection = dedent_selection
self._right_pad_options = right_pad_options
self._cursor = cursor if cursor is not None else self.default_cursor
self._style = style if style is not None else self.default_style
@ -259,6 +260,13 @@ class CliMenu:
raise ValueError("Initial position {} is out of range, needs to be in range of [0, {})"
.format(self._initial_pos, self._item_num))
if self._right_pad_options:
# pad all item labels with spaces to have the same length
max_item_len = max([len(_item.text) for _item in self._items if _item.focusable])
for item in self._items:
if item.focusable:
item.text += " " * (max_item_len - len(item.text))
def _accept(self, event):
self._success = True
event.app.exit()

9
examples/cursorless.py Normal file
View File

@ -0,0 +1,9 @@
#!/usr/bin/env python3
from clintermission import CliMenu, CliMenuTheme
q = ["Foo", "Bar", "Baz baz baz baz baz"]
m = CliMenu(q, "Time to choose:\n", style=CliMenuTheme.BOLD_HIGHLIGHT,
cursor='', option_prefix=' ', option_suffix=' ', right_pad_options=True)
m.get_selection()
print("You selected", m.get_selection())