7

我正在使用 urwid,它是一个 Python“框架”,用于在 ncurses 中设计终端用户界面。虽然我无法在 urwid 中做一件事,但在诅咒中很容易 - 使光标不可见。就像现在一样,在选择按钮时光标是可见的,而且看起来很丑。有没有办法禁用它?

4

4 回答 4

6

我同意 an 上闪烁的光标urwid.Button看起来有点蹩脚,所以我想出了一个隐藏它的解决方案。在 urwid 中,Button该类只是WidgetWrap包含一个SelectableIcon和两个 Text 小部件(封闭的“<”和“>”)的子类。默认情况下,SelectableIcon该类将光标位置设置为标签的第一个字符。通过子类SelectableIcon化,修改光标位置,然后将其包装到urwid.WidgetWrap子类中,您可以创建自己的自定义按钮,该按钮可以完成内置的所有技巧Button,甚至更多。

这是我的项目中的样子。

在此处输入图像描述

import urwid

class ButtonLabel(urwid.SelectableIcon):
    def __init__(self, text):
        """
        Here's the trick: 
        we move the cursor out to the right of the label/text, so it doesn't show
        """
        curs_pos = len(text) + 1 
        urwid.SelectableIcon.__init__(self, text, cursor_position=curs_pos)

接下来,您可以将一个ButtonLabel对象与任何其他对象一起包装到一个WidgetWrap子类中,该子类将成为您的自定义按钮类。

class FixedButton(urwid.WidgetWrap):
    _selectable = True
    signals = ["click"]
    def __init__(self, label):
        self.label = ButtonLabel(label)
        # you could combine the ButtonLabel object with other widgets here
        display_widget = self.label 
        urwid.WidgetWrap.__init__(self, urwid.AttrMap(display_widget, None, focus_map="button_reversed"))

    def keypress(self, size, key):
        """
        catch all the keys you want to handle here
        and emit the click signal along with any data 
        """
        pass

    def set_label(self, new_label):
        # we can set the label at run time, if necessary
        self.label.set_text(str(new_label))

    def mouse_event(self, size, event, button, col, row, focus):
        """
        handle any mouse events here
        and emit the click signal along with any data 
        """
        pass

在这段代码中,子类中实际上并没有太多的小部件组合FixedButton WidgetWrap,但是您可以在按钮的边缘添加一个“ [”和“ ]”,将其包装成一个LineBox等。如果这一切都是多余的,你可以移动事件处理函数到ButtonLabel类中,并使其在被单击时发出信号。

要在用户移动按钮时使按钮反转,请将其包装AttrMap并设置focus_map为某个调色板条目(button_reversed在我的情况下为“”)。

于 2017-04-16T17:15:51.350 回答
3

在醉酒大师的回答的基础上,我已经尽可能地清理了解决方案。

urwid.SelectableIcon基本上是一个urwid.Text带有这个丑陋的闪烁光标的字段。因此,与其覆盖urwid.SelectableIcon并将其打包成urwid.WidgetWrap,让我们urwid.Text直接采用 并使其可选择并对按钮/鼠标激活做出反应(灵感来自urwid 的简单菜单教程):

import urwid

choices = u'Chapman Cleese Gilliam Idle Jones Palin'.split()

class ListEntry(urwid.Text):
    _selectable = True

    signals = ["click"]

    def keypress(self, size, key):
        """
        Send 'click' signal on 'activate' command.
        """
        if self._command_map[key] != urwid.ACTIVATE:
            return key

        self._emit('click')

    def mouse_event(self, size, event, button, x, y, focus):
        """
        Send 'click' signal on button 1 press.
        """
        if button != 1 or not urwid.util.is_mouse_press(event):
            return False

        self._emit('click')
        return True

def menu(title, choices):
    body = [urwid.Text(title), urwid.Divider()]
    for c in choices:
        button = ListEntry(c)
        urwid.connect_signal(button, 'click', item_chosen, c)
        body.append(urwid.AttrMap(button, None, focus_map='reversed'))
    return urwid.ListBox(urwid.SimpleFocusListWalker(body))

def item_chosen(button, choice):
    response = urwid.Text([u'You chose ', choice, u'\n'])
    done = ListEntry(u'Ok')
    urwid.connect_signal(done, 'click', exit_program)
    main.original_widget = urwid.Filler(urwid.Pile([response,
                                                    urwid.AttrMap(done, None, focus_map='reversed')]))

def exit_program(button):
    raise urwid.ExitMainLoop()

main = urwid.Padding(menu(u'Pythons', choices), left=2, right=2)
top = urwid.Overlay(main, urwid.SolidFill(u'\N{MEDIUM SHADE}'),
                    align='center', width=('relative', 60),
                    valign='middle', height=('relative', 60),
                    min_width=20, min_height=9)
urwid.MainLoop(top, palette=[('reversed', 'standout', '')]).run()

奇迹般有效:

在此处输入图像描述

于 2019-06-25T17:18:43.570 回答
2

urwid使用curs_set函数,但不会在任何地方将其作为类方法公开。有人可以修改 urwid 以允许使用此方法;否则没有可靠的方法可以做到这一点。

您可能会将其报告为问题

于 2016-01-08T02:22:24.910 回答
1

按照醉酒大师的回答,但使用“微创手术”:

class ButtonLabel(urwid.SelectableIcon):
    '''
    use Drunken Master's trick to move the cursor out of view
    '''
    def set_text(self, label):
        '''
        set_text is invoked by Button.set_label
        '''
        self.__super.set_text(label)
        self._cursor_position = len(label) + 1


class MyButton(urwid.Button):
    '''
    - override __init__ to use our ButtonLabel instead of urwid.SelectableIcon

    - make button_left and button_right plain strings and variable width -
      any string, including an empty string, can be set and displayed

    - otherwise, we leave Button behaviour unchanged
    '''
    button_left = "["
    button_right = "]"

    def __init__(self, label, on_press=None, user_data=None):
        self._label = ButtonLabel("")
        cols = urwid.Columns([
            ('fixed', len(self.button_left), urwid.Text(self.button_left)),
            self._label,
            ('fixed', len(self.button_right), urwid.Text(self.button_right))],
            dividechars=1)
        super(urwid.Button, self).__init__(cols)

        if on_press:
            urwid.connect_signal(self, 'click', on_press, user_data)

        self.set_label(label)

在这里,我们只修改按钮的外观,其他方面保持其行为不变。

于 2017-06-21T17:47:44.777 回答