Search code examples
widgetfocuskeypressurwid

How to change key mapping for urwid widget navigation?


How can I set/change the CommandMap in a SimpleFocusListWalker? 'up' and 'down' keystrokes are associated with changing the focus by default. I'd like to modify these to something else.

Is this possible?


Solution

  • One easy and effective solution is to override the keypress method of ListBox and substitute the keys:

    import urwid
    
    class MyBox(urwid.ListBox):
        
        def keypress(self, size, key): 
            if key in {'up', 'down'}:
                print('use (shift) tab to move cursor.')
                return
            key_map = {
                "shift tab": "up",
                "tab": "down",
            }
            super().keypress(size, key_map[key])
    
    button_list = [urwid.Button(str(k)) for  k in range(10)]
    urwid.MainLoop(MyBox(button_list)).run()
    

    Using the built in keypress method is preferable, as it has niceties like skipping urwid.Divider() widgets and won't allow to focus to go out of bounds.