如何在pythonpromptoolkit中将pageup/pagedown键绑定添加到TextArea?

2024-09-26 18:08:40 发布

您现在位置:Python中文网/ 问答频道 /正文

让我们以calculator.py为例

要添加与鼠标滚轮配合使用的滚动条,您需要更改:

output_field = TextArea(style="class:output-field", text=help_text)

calculator.py without scrollbar

致:

output_field = TextArea(style="class:output-field", text=help_text, scrollbar=True)

calculator.py with scrollbar

但是,您会添加或更改什么来使用page up(向上翻页)和page down(向下翻页)键滚动文本区域

# The key bindings.
kb = KeyBindings()

@kb.add("pageup")
def _(event):
    # What goes here?
    pass

@kb.add("pagedown")
def _(event):
    # What goes here?
    pass

Tags: texteventaddfieldoutputkbstyledef
1条回答
网友
1楼 · 发布于 2024-09-26 18:08:40

改变焦点

最简单的方法可能是导入focus_next(或focus_previous

from prompt_toolkit.key_binding.bindings.focus import focus_next

并将其绑定到控制空间(或其他任何内容)

# The key bindings.
kb = KeyBindings()

kb.add("c-space")(focus_next)

集中注意力

您还可以将注意力集中在input_field,导入scroll_page_upscroll_page_down

from prompt_toolkit.key_binding.bindings.page_navigation import scroll_page_up, scroll_page_down

然后将焦点切换到output_field,调用scroll_page_up/scroll_page_down,最后将焦点切换回input_field

# The key bindings.
kb = KeyBindings()

@kb.add("pageup")
def _(event):
    w = event.app.layout.current_window
    event.app.layout.focus(output_field.window)
    scroll_page_up(event)
    event.app.layout.focus(w)

@kb.add("pagedown")
def _(event):
    w = event.app.layout.current_window
    event.app.layout.focus(output_field.window)
    scroll_page_down(event)
    event.app.layout.focus(w)

相关问题 更多 >

    热门问题