以下示例(取自此处:http://urwid.org/tutorial/index.html)展示了如何将键值传递给回调函数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()
如何使用取决于系统状态的回调将另一个参数传递给 show_or_exit
,就像这样?
...: 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()
最佳答案
因此,有多种方法可以做到这一点。您可以使用全局变量,但我想您可能会问这个问题,因为您想要一种更好的方法来做到这一点(另外,全局变量无论如何都会笨拙地改变状态)。
对于像本例这样的小程序,一种技术可能是使用一个全局对象来存储状态:
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 类将从 using the attrs library 中受益匪浅。 。强烈推荐! :)
对于更复杂的程序,我建议构建支持回调事件的自定义小部件并单独管理状态:您可以看到 an example of implementing that in this solitaire game .
关于function - 使用回调函数传递附加参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49162143/