This is a solution using curses
(at the end it waits for the x
key to end the program):
#!/usr/bin/python
import time
import sys
import curses
def questionloop(stdscr):
stdscr.addstr("Question: ")
curses.echo()
while (1):
answer = stdscr.getstr()
curses.flushinp()
stdscr.clear()
stdscr.addstr("This is correct!")
doit = stdscr.getch()
if doit == ord('x'):
stdscr.addstr("Exiting!\n")
break
curses.wrapper(questionloop)
And this is an example using urwid
:
import urwid
def exit_on_q(key):
if key in ('q', 'Q'):
raise urwid.ExitMainLoop()
class QuestionBox(urwid.Filler):
def keypress(self, size, key):
if key != 'enter':
return super(QuestionBox, self).keypress(size, key)
self.original_widget = urwid.Text(
u"%s\n" %
edit.edit_text)
edit = urwid.Edit(u"Question: \n")
fill = QuestionBox(edit)
loop = urwid.MainLoop(fill, unhandled_input=exit_on_q)
loop.run()
Another (probably most concise) solution, from Veedrac's answer, would be to use blessings
:
from blessings import Terminal
term = Terminal()
question = "{t.red}{}{t.normal}{t.bold}".format
answer = "{t.normal}{t.move_up}{t.green}{}{t.normal}{t.clear_eol}".format
input(question("Question: ", t=term))
print(answer("Correct!", t=term))
urwid
example. – Trepang\r
won't work here because the user pressed enter (otherwiseraw_input()
won't return) i.e., you need to go up one line. A lightweight solution is to use ANSI codes for positioning e.g.,blessings
package provides a simpler (thancurses
) interface (to move up, usemove_up
).blessings
might even work on Windows withcolorama
(it needs testing). – Valeryvalerye