Bokeh布局中按钮与文本输入框垂直对齐问题的解决方案问询
I've run into this exact alignment problem with Bokeh before—when you put a Button next to a labeled TextInput in a row, their vertical positions end up misaligned because of the TextInput's built-in label structure. Here are a few practical workarounds to fix this:
Example Code (The Misaligned Version)
# hello.py from bokeh.io import curdoc from bokeh.layouts import column, row from bokeh.models.widgets import TextInput, Button, Paragraph # create some widgets button = Button(label="Say HI") input = TextInput(value="Bokeh") output = Paragraph() # add a callback to a widget def update(): output.text = "Hello, " + input.value button.on_click(update) # create a layout for everything layout = column(row(button, input), output) # add the layout to curdoc curdoc().add_root(layout)
Workaround 1: Adjust TextInput's Inline Styles
You can tweak the TextInput's margin to shift it vertically into alignment with the Button. The exact value might need a small adjustment based on your Bokeh version:
input = TextInput(value="Bokeh", styles={"margin-top": "6px"})
Workaround 2: Match Component Structure with a Container
Wrap the Button in a container that mimics the height of the TextInput's label area. Using an empty Paragraph to take up the label space works well:
# Create a container to match TextInput's label height button_container = column(Paragraph(text="", width=0), button, width=120) layout = column(row(button_container, input), output)
This ensures the Button's clickable area lines up perfectly with the TextInput's input field.
Workaround 3: Global CSS Fix
If you have multiple instances of this layout in your app, add a global style tag to standardize alignment for all components:
curdoc().add_style_tag(""" .bk-root .bk-input-group { vertical-align: middle; } .bk-root .bk-btn { vertical-align: middle; margin-top: 0; } """)
This targets Bokeh's built-in CSS classes to force consistent vertical alignment across all rows with these widgets.
Note: This is a known layout issue in Bokeh that's been tracked in the project's issue system.
内容的提问来源于stack exchange,提问作者Yael Green

