2

The following example (taken from here: http://urwid.org/tutorial/index.html) shows how to pass key values to a callback function show_or_exit.

import urwid

def show_or_exit(key):
    if key in ('q', 'Q'):
        raise urwid.ExitMainLoop()
    txt.set_text(repr(key))

txt = urwid.Text(u"Hello World")
fill = urwid.Filler(txt, 'top')
loop = urwid.MainLoop(fill, unhandled_input=show_or_exit)
loop.run()

How can I pass another argument to show_or_exit with this callback that depend on the state of the system, that would be something like this?

...: param_val = 4
...:
...: def my_fun():
...:     #do something
...:     return param_val
...:
...: def show_or_exit(key, param_val):
...:     if key in ('q', 'Q'):
...:         raise urwid.ExitMainLoop()
...:     txt.set_text(repr(key))
...:     do_something(param_val)
...:
...: txt = urwid.Text(u"Hello World")
...: fill = urwid.Filler(txt, 'top')
...: loop = urwid.MainLoop(fill, unhandled_input=show_or_exit)
...: loop.run()
4

1 回答 1

2

因此,有几种方法可以做到这一点。您可以使用全局变量,但我想您可能会问这个问题,因为您想要一种更好的方法(另外,全局变量无论如何都会笨拙地改变状态)。

对于本例中的小程序,一种技术可能是使用一个全局对象来存储状态:

import urwid
from functools import partial


class State(object):
    param1 = 1
    param2 = 'ola'

    def __repr__(self):
        return 'State(param1={}, param2={})'.format(self.param1, self.param2)


def show_or_exit(app_state, key):
    if key in ('q', 'Q'):
        raise urwid.ExitMainLoop()
    app_state.param1 += 1
    txt.set_text('key: {!r} state: {!r}'.format(key, app_state))


txt = urwid.Text(u"Hello World")
fill = urwid.Filler(txt, 'top')
app_state = State()
callback = partial(show_or_exit, app_state)
loop = urwid.MainLoop(fill, unhandled_input=callback)
loop.run()

出于说明目的,我将这个示例保持在最小限度,但是 State 类将从使用 attrs 库中受益很多。强烈推荐!:)

对于更复杂的程序,我建议构建支持回调事件的自定义小部件并单独管理状态:您可以在这个纸牌游戏中看到一个实现它的示例

于 2018-03-10T19:33:25.890 回答