def main():
palette = [
('body','black','dark cyan', 'standout'),
('foot','light gray', 'black'),
('key','light cyan', 'black', 'underline'),
('title', 'white', 'black',),
]
footer_text = [
('title', "Fibonacci Set Viewer"), " ",
('key', "UP"), ", ", ('key', "DOWN"), ", ",
('key', "PAGE UP"), " and ", ('key', "PAGE DOWN"),
" move view ",
('key', "Q"), " exits",
]
def exit_on_q(input):
if input in ('q', 'Q'):
raise urwid.ExitMainLoop()
listbox = urwid.ListBox(FibonacciWalker())
footer = urwid.AttrMap(urwid.Text(footer_text), 'foot')
view = urwid.Frame(urwid.AttrWrap(listbox, 'body'), footer=footer)
loop = urwid.MainLoop(view, palette, unhandled_input=exit_on_q)
loop.run()
python类MainLoop()的实例源码
def input_filter(self, input, raw_input):
if 'q' in input or 'Q' in input:
raise urwid.ExitMainLoop()
# handle other keystrokes
for k in input:
try:
self.wrap_keypress(k)
self.event = None
self.view.footer = None
except CalcEvent, e:
# display any message
self.event = e
self.view.footer = e.widget()
# remove all input from further processing by MainLoop
return []
def __init__(self, client):
self.client = client
self.screen = urwid.raw_display.Screen()
# self.screen = self.DummyScreen()
self.frame = urwid.Frame(
client.default_view,
footer=urwid.Text("", align='center'),
)
self.client.frame = self.frame
self.urwid_loop = urwid.MainLoop(
self.frame,
screen=self.screen,
palette=palette,
event_loop=self.FixedAsyncLoop(loop=client.loop),
unhandled_input=client.handle_keypresses,
pop_ups=True
)
def display(self):
# this method starts the main loop and such
self.loop = urwid.MainLoop(self.pile,
self.palette,
handle_mouse = False,
unhandled_input = self.keypress,
pop_ups = True)
self.loop.screen.set_terminal_properties(colors=256)
self.register_palette()
self.term.main_loop = self.loop
try:
self.loop.run()
except:
return 'failure'
with open(TABS_PATH, 'a') as f:
f.write(str(self.layout))
return 'exit'
def __init__(self, connection_name):
try:
self.connection_name = connection_name
frame = self.getFrame()
comp = self.getCommandProcessor()
self.loop = urwid.MainLoop(urwid.AttrMap(frame, 'bg'),
unhandled_input=comp.onInput,
palette=themes['dark'])
self.consoleMonitor = ScreepsConsoleMonitor(connection_name,
self.consoleWidget,
self.listWalker,
self.loop)
comp.setDisplayWidgets(self.loop,
frame,
self.getConsole(),
self.getConsoleListWalker(),
self.getEdit(),
self.consoleMonitor)
self.loop.run()
except KeyboardInterrupt:
exit(0)
def __init__(self):
self.prefs = bbjrc("load")
self.mode = None
self.thread = None
self.usermap = {}
self.window_split = False
self.last_pos = None
# these can be changed and manipulated by other methods
self.walker = urwid.SimpleFocusListWalker([])
self.box = ActionBox(self.walker)
self.body = urwid.AttrMap(
urwid.LineBox(
self.box,
title=self.prefs["frame_title"],
**frame_theme()),
"default"
)
self.loop = urwid.MainLoop(
urwid.Frame(self.body),
palette=colormap,
handle_mouse=self.prefs["mouse_integration"])
def display(self, f):
def handle_input(key):
if key in ('q', 'Q'):
raise urwid.ExitMainLoop()
elif key in ('right', 'j', ' '):
if self.slide_id < len(self.sd) - 1:
self.slide_id += 1
elif key in ('left', 'k'):
if self.slide_id > 0:
self.slide_id -= 1
self.update_display()
self.load_charset()
self.sd = list(yaml.load_all(f))
self.slide_id = 0
self.update_display()
txt = urwid.Text(u"Presenting...")
fill = urwid.Filler(txt, 'bottom')
urwid.MainLoop(fill, unhandled_input=handle_input).run()
def connection_made(self, transport):
print("Got a client!")
self.transport = transport
# StreamReader is super convenient here; it has a regular method on our
# end (feed_data), and a coroutine on the other end that will
# faux-block until there's data to be read. We could also just call a
# method directly on the screen, but this keeps the screen somewhat
# separate from the protocol.
self.reader = asyncio.StreamReader(loop=loop)
screen = AsyncScreen(self.reader, transport)
main_widget = build_widgets()
self.urwid_loop = urwid.MainLoop(
main_widget,
event_loop=urwid.AsyncioEventLoop(loop=loop),
screen=screen,
unhandled_input=unhandled,
)
self.urwid_loop.start()
def __init__(self):
"""
Initializes the application and starts the event loop.
Note:
Before anything else, the __preliminaries() method will be called,
setting up the client factory.
"""
self.__preliminaries()
# Initiate the main loop with a splash screen as the first widget.
# Use defaultPalette defined in globals, and the Twisted reactor loop.
self.mainLoop = urwid.MainLoop(EmptyFrame("Welcome to ChatMaster 3000", self), defaultPalette, event_loop=urwid.TwistedEventLoop())
# Put the screen into 256-color mode
self.mainLoop.screen.set_terminal_properties(colors=256)
# Show the login screen
self.__transitionToFrame(LoginFrame, 1)
self.mainLoop.run()
def __init__(self, controller, style):
# Shared objects to help event handling.
self.events = Queue()
self.lock = Lock()
self.view = MainWindow(controller)
self.screen = raw_display.Screen()
self.screen.set_terminal_properties(256)
self.loop = MainLoop(widget=self,
palette=style,
screen=self.screen,
unhandled_input=Tui.exit_handler,
pop_ups=True)
self.pipe = self.loop.watch_pipe(self.update_ui)
self.loop.set_alarm_in(0.1, Tui.update_timer, self.view.logo.timer)
super(Tui, self).__init__(self.view)
connect_signal(self.view.issues_table, 'refresh', lambda source: self.loop.draw_screen())
connect_signal(self.view.stat_table, 'refresh', lambda source: self.loop.draw_screen())
def setup_view(self):
placeholder = urwid.SolidFill()
self.loop = urwid.MainLoop(
placeholder, PALETTE, unhandled_input=self.key_handler)
self.loop.widget = urwid.AttrMap(placeholder, 'bg')
#self.loop.widget._command_map['tab'] = 'cursor down'
#self.loop.widget._command_map['shift tab'] = 'cursor up'
self.loop.screen.set_terminal_properties(colors=256)
self.cards.welcome()
def main():
import argparse
parser = argparse.ArgumentParser(description=__doc__)
parser.parse_args()
app = GameApp()
loop = urwid.MainLoop(
urwid.Filler(app.main_layout, valign='top'),
PALETTE,
unhandled_input=exit_on_q,
)
loop.run()
def run(calendar, server):
top = EventWidget(valign='top', calendar=calendar, server=server)
loop = urwid.MainLoop(top)
loop.run()
def start_tui(args):
txt = urwid.Text(u"Hello World")
fill = urwid.Filler(txt, "top")
loop =urwid.MainLoop(fill, unhandled_input=exit_on_q)
loop.run()
def run(self):
self.main_loop = urwid.MainLoop(self.w_main, palette=self.palette,
unhandled_input=self.unhandled_keypress)
self.child_pipe = self.main_loop.watch_pipe(self.received_output)
self.init_test_data()
logger.debug('Running main urwid loop')
self.main_loop.run()
def __init__(self, pubpen, cli_args):
super().__init__(pubpen, cli_args)
# Note: We don't have any extra command line args
# Windows
self.title_card = TitleScreen(pubpen)
self.login_screen = LoginScreen(pubpen)
self.main_window = MainScreen(pubpen)
self.root_win = urwid.Frame(urwid.SolidFill(' '))
# Arrange the widgets
self.show_title_card()
# Connect to UI events
urwid.connect_signal(self.title_card, 'close_title_card', self.show_login_screen)
urwid.connect_signal(self.login_screen, 'logged_in', self.show_main_window)
# Setup the main loop
self.urwid_loop = urwid.MainLoop(self.root_win,
event_loop=urwid.AsyncioEventLoop(loop=self.pubpen.loop),
palette=(('reversed', 'standout', ''),),)
def run(self):
self.loop = urwid.MainLoop(self.frame, palette, handle_mouse=False,
unhandled_input=self.unhandled_keypress)
self.loop.set_alarm_in(0, lambda loop, data: self.reload_file())
try:
self.loop.run()
except Exception as e:
self.loop.stop()
print(traceback.format_exc())
def setup_view(self):
placeholder = urwid.SolidFill()
self.loop = urwid.MainLoop(
placeholder, PALETTE, unhandled_input=self.key_handler)
self.loop.widget = urwid.AttrMap(placeholder, 'bg')
#self.loop.widget._command_map['tab'] = 'cursor down'
#self.loop.widget._command_map['shift tab'] = 'cursor up'
self.loop.screen.set_terminal_properties(colors=256)
self.cards.welcome()
def run(movies):
global loop
list_view = ListView(movies)
loop = urwid.MainLoop(list_view, palette, unhandled_input=exit_on_q)
loop.screen.set_terminal_properties(colors=256)
loop.run()
return loop.data if hasattr(loop, 'data') else None
def loop(self, handle_mouse=False):
self.eloop=urwid.MainLoop(self, self.PALLETE, handle_mouse=handle_mouse)
self._eloop_thread=threading.current_thread()
self.eloop.run()
def loop(self, handle_mouse=False):
self.eloop=urwid.MainLoop(self, self.PALLETE, handle_mouse=handle_mouse)
self._eloop_thread=threading.current_thread()
self.eloop.run()
def wipe_screen(*_):
"""
A crude hack to repaint the whole screen. I didnt immediately
see anything to acheive this in the MainLoop methods so this
will do, I suppose.
"""
app.loop.stop()
call("clear", shell=True)
app.loop.start()
def __main__():
MAIN_LOOP = urwid.MainLoop(LAYOUT, PALETTE, unhandled_input=exit_on_cr)
MAIN_LOOP.run()
def __init__(self, db=None, cmd=None):
self.db = papis.database.Database()
self.header_string = "Papis"
self.status_string = "q: quit buffer, Q: quit Papis, ?: help"
self.view = urwid.Frame(urwid.SolidFill())
self.set_header()
self.set_status()
if not cmd:
cmd = ['search', '']
if cmd[0] == 'search':
query = ' '.join(cmd[1:])
self.buffer = Search(self, query)
elif cmd[0] == 'bibview':
query = ' '.join(cmd[1:])
self.buffer = Bibview(self, query)
elif cmd[0] == 'help':
target = None
if len(cmd) > 1:
target = cmd[1]
if isinstance(target, str):
target = None
self.buffer = Help(self, target)
else:
self.buffer = Help(self)
self.set_status("Unknown command '%s'." % (cmd[0]))
self.merge_palette(self.buffer)
self.view.body = urwid.AttrMap(self.buffer, 'body')
self.mainloop = urwid.MainLoop(
self.view,
self.palette,
unhandled_input=self.keypress,
handle_mouse=False,
)
def loop(self, handle_mouse=False):
self.eloop = urwid.MainLoop(self, self.PALLETE, handle_mouse=handle_mouse)
self._eloop_thread = threading.current_thread()
self.eloop.run()
def exit_loop_on_q_esc(key: str):
"""End urwid.MainLoop on keypress of 'q' or 'esc'."""
if key in {'q', 'Q', 'esc'}:
raise urwid.ExitMainLoop()
def select_mod(
choices: Sequence[Mod],
header: Optional[str] = None,
footer: Optional[str] = None,
) -> Optional[Mod]:
"""Present user with a TUI menu and return his choice.
Keyword arguments:
choices: The :class:`Mod`s to choose from.
header: Optional menu heading.
footer: Optional menu footing.
Returns:
The selected mod.
"""
menu = ModMenu(choices)
head = urwid.Text(('title', header), align='center') if header else None
foot = urwid.Text(('description', footer), align='center') if footer else None # noqa: E501
if head or foot:
top = urwid.Frame(menu, head, foot)
else:
top = menu
try:
colors = curses.tigetnum('colors')
except curses.error: # Uninitialized terminal
colors = 16
event_loop = urwid.MainLoop(
top,
palette=ModMenu.palette,
unhandled_input=exit_loop_on_q_esc,
)
event_loop.screen.set_terminal_properties(colors=colors)
event_loop.run()
return menu.chosen
def main(self):
self.view, self.exit_view = self.setup_view()
self.loop = urwid.MainLoop(self.view, self.palette,
unhandled_input=self.unhandled_input)
self.loop.run()
def main(self):
"""Run the program."""
self.loop = urwid.MainLoop(self.view, self.palette,
unhandled_input=self.unhandled_input)
self.loop.run()
# on exit, write the flagged filenames to the console
names = [escape_filename_sh(x) for x in get_flagged_names()]
print " ".join(names)
def main(self):
self.loop = urwid.MainLoop(self.view, self.view.palette)
self.loop.run()