我正在使用Urwid组装一个小控制台应用程序。我使用了 Urwid 教程(请参阅 http://urwid.org/tutorial/(中描述的模式来处理按键事件。
例如
def on_unhandled_input(key):
elif key in ('n'):
create_new()
elif key in ('q'):
raise urwid.ExitMainLoop()
main_loop = urwid.MainLoop(layout, unhandled_input=on_unhandled_input)
main_loop.run()
我的问题是unhandled_input似乎捕获了鼠标单击,这导致我的处理程序出错
TypeError: 'in <string>' requires string as left operand, not tuple
过滤按键并放弃鼠标单击的最佳方法是什么?
这里的问题是语法('n')
和('q')
正在创建字符串而不是元组。对于键来说,这不是问题,因为in
运算符用于检查字符串是否在字符串内:
>>> 'n' in 'n'
True
>>> 'n' in ('n')
True
但这失败并显示错误:
>>> ('mouse', 'right') in ('n')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not tuple
要解决此问题,您可以为元组语法添加逗号,请尝试:
def on_unhandled_input(key):
elif key in ('n',): # <-- notice the added comma here
create_new()
elif key in ('q',): # <-- and here too
raise urwid.ExitMainLoop()
作为替代方案,您可以使用==
进行比较:
def on_unhandled_input(key):
elif key == 'n': # <-- notice the added comma here
create_new()
elif key == 'q': # <-- and here too
raise urwid.ExitMainLoop()