Created
April 25, 2017 18:20
-
-
Save eliasdorneles/941ed99c08b24b9042fd05b0a350a549 to your computer and use it in GitHub Desktop.
Draw a square in the screen, move it with arrow keys -- experimenting with urwid
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
"""Draw a square in the screen, move it with arrow keys | |
""" | |
from __future__ import print_function, absolute_import, division | |
import urwid | |
BLOCK = u""" | |
╭───╮ | |
│ │ | |
╰───╯ | |
""".strip() | |
BOX_ROWS = len(BLOCK.splitlines()) | |
BOX_COLS = len(BLOCK.splitlines()[0]) | |
def exit_on_q_or_esc(key): | |
if key in ('esc', 'q', 'Q'): | |
raise urwid.ExitMainLoop() | |
class MoveableBox(urwid.WidgetWrap): | |
def selectable(self): | |
return True | |
def __init__(self): | |
self._padding_left = 0 | |
self._padding_top = 0 | |
self.text = urwid.Text(BLOCK) | |
self.container = self._build_widget() | |
self.pile = urwid.Pile([]) | |
self.redraw() | |
super(MoveableBox, self).__init__(self.pile) | |
@property | |
def padding_left(self): | |
return self._padding_left | |
@padding_left.setter | |
def padding_left(self, value): | |
self._padding_left = value if value > 0 else 0 | |
@property | |
def padding_top(self): | |
return self._padding_top | |
@padding_top.setter | |
def padding_top(self, value): | |
self._padding_top = value if value > 0 else 0 | |
def _build_widget(self): | |
filler = urwid.Filler(self.text, 'top', top=self.padding_top) | |
return urwid.Padding(filler, left=self.padding_left) | |
def redraw(self): | |
self.pile.contents[:] = [(self._build_widget(), self.pile.options())] | |
def keypress(self, size, key): | |
maxcol, maxrow = size | |
h_increment = 2 | |
v_increment = 1 | |
if key in ('right'): | |
if maxcol > self.padding_left + BOX_COLS + h_increment: | |
self.padding_left += h_increment | |
self.redraw() | |
elif key in ('left'): | |
self.padding_left -= h_increment | |
self.redraw() | |
elif key in ('up'): | |
self.padding_top -= v_increment | |
self.redraw() | |
elif key in ('down'): | |
if maxrow > self.padding_top + BOX_ROWS: | |
self.padding_top += v_increment | |
self.redraw() | |
else: | |
return super(MoveableBox, self).keypress(size, key) | |
def run(args): | |
box = MoveableBox() | |
loop = urwid.MainLoop(box, unhandled_input=exit_on_q_or_esc) | |
loop.run() | |
if '__main__' == __name__: | |
import argparse | |
parser = argparse.ArgumentParser(description=__doc__) | |
args = parser.parse_args() | |
run(args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment