首页 > 解决方案 > 使用提示工具包全屏应用程序均匀间隔的列,无论内容宽度如何

问题描述

使用prompt_toolkit,我想创建一个均匀分布的垂直布局,而不管每个窗口(全屏应用程序)中内容的宽度如何。不良行为 - 当更改一个 [或多个] 控件中的内容时,会重新计算布局以适应更宽或更窄的动态内容。

有没有办法让给定屏幕尺寸的布局静态化?即,仅在初始化或调整大小时渲染窗口,保持布局列均匀分布?

下面的示例代码(按下c以在任一列上注入随机长度的内容,布局宽度发生变化)。即使添加用户消息也可能导致在足够窄的终端上初始化不均匀的宽度。

from random import randint

from prompt_toolkit.application import Application
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.layout.containers import VSplit, Window
from prompt_toolkit.layout.controls import FormattedTextControl
from prompt_toolkit.layout.layout import Layout

user_msg = "press 'c' to change, 'q' to quit"

body = VSplit(
    [
        Window(FormattedTextControl(text=user_msg)),
        Window(width=1, char="|"),
        Window(FormattedTextControl()),
    ]
)

kb = KeyBindings()


@kb.add("c")
def change_content(event):
    for w in event.app.layout.find_all_windows():
        prev_width = f"prev_width: {w.render_info.window_width}"
        rand_str = "*" * randint(1, 50)
        w.content.text = "\n".join([prev_width, rand_str])


@kb.add("q")
def quit(event):
    event.app.exit()


layout = Layout(body)
app = Application(layout=layout, key_bindings=kb, full_screen=True)
app.run()

标签: pythontuiprompt-toolkit

解决方案


传递参数 ignore_content_width 有效。

body = VSplit(
    [
        Window(FormattedTextControl(text=user_msg), ignore_content_width=True),
        Window(width=1, char="|"),
        Window(FormattedTextControl(), ignore_content_width=True),
    ]
)

推荐阅读