在 urwid 中,有没有办法让子小部件根据屏幕重绘操作更改其属性?
具体来说,如果我有一个带有很长字符串的按钮小部件:
mybutton = urwid.Button(<some very long string>)
当终端重新调整为小于字符串长度的列宽时,按钮是否可以仅显示部分字符串?相当于:
mybutton = urwid.Button(<some very long...>)
就像现在一样,urwid 尝试包装按钮标签,这在我的界面上下文中看起来很难看。
在 urwid 中,有没有办法让子小部件根据屏幕重绘操作更改其属性?
具体来说,如果我有一个带有很长字符串的按钮小部件:
mybutton = urwid.Button(<some very long string>)
当终端重新调整为小于字符串长度的列宽时,按钮是否可以仅显示部分字符串?相当于:
mybutton = urwid.Button(<some very long...>)
就像现在一样,urwid 尝试包装按钮标签,这在我的界面上下文中看起来很难看。
我认为实现这一点的最简单方法是将这种行为实现为自定义小部件,它包装了原版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()