更改屏幕重绘urwid上的按钮标签

时间:2017-01-10 14:34:53

标签: python-3.x button urwid

在urwid中,子窗口小部件是否有办法根据屏幕重绘操作更改其属性?

具体来说,如果我有一个带有一些很长字符串的按钮小部件:

mybutton = urwid.Button(<some very long string>)

当终端重新调整为小于字符串长度的列宽时,按钮是否有一种方法只显示字符串的一部分?相当于:

mybutton = urwid.Button(<some very long...>)

就像现在一样,urwid尝试包装按钮标签,这在我的界面环境中看起来很难看。

1 个答案:

答案 0 :(得分:0)

我认为实现这一目标的最简单方法是将此行为实现为custom widget,它包装了vanilla urwid.Button,但强制它只在一行中呈现 - 这是一个完全正常的工作例如:

from __future__ import print_function, absolute_import, division
import urwid    

class MyButton(urwid.WidgetWrap):
    def __init__(self, *args, **kw):
        self.button = urwid.Button(*args, **kw)
        super(MyButton, self).__init__(self.button)

    def rows(self, *args, **kw):
        return 1

    def render(self, size, *args, **kw):
        cols = size[0]
        maxsize = cols - 4  # buttons use 4 chars to draw < > borders
        if len(self.button.label) > maxsize:
            new_label = self.button.label[:maxsize - 3] + '...'
            self.button.set_label(new_label)
        return super(MyButton, self).render(size, *args, **kw)


def show_or_exit(key):
    if key in ('q', 'Q', 'esc'):
        raise urwid.ExitMainLoop()    


if __name__ == '__main__':
    # demo:
    widget = urwid.Pile([
        urwid.Text('Some buttons using urwid vanilla urwid.Button widget:\n'),
        urwid.Button('Here is a little button with really a really long string for label, such that it can be used to try out a problem described in Stackoverflow question'),
        urwid.Button('And here is another button, also with a really really long string for label, for the same reason as the previous one'),
        urwid.Button('And a short one'),
        urwid.Text('\n\n\nSame buttons, with a custom button widget:\n'),
        MyButton('Here is a little button with really a really long string for label, such that it can be used to try out a problem described in Stackoverflow question'),
        MyButton('And here is another button, also with a really really long string for label, for the same reason as the previous one'),
        MyButton('And a short one'),
        urwid.Columns([
            MyButton('Here is a little button with really a really long string for label, such that it can be used to try out a problem described in Stackoverflow question'),
            MyButton('And here is another button, also with a really really long string for label, for the same reason as the previous one'),
        ]),
    ])
    widget = urwid.Filler(widget, 'top')
    loop = urwid.MainLoop(widget, unhandled_input=show_or_exit)
    loop.run()

了解更多