Extend the centering Q in the FAQ

Add an example of how to center multiple widgets, rather than center the
bounding box of multiple widgets.
This commit is contained in:
Dave Pearson
2023-03-07 10:16:51 +00:00
parent fcc16c0e59
commit fed11e50f9
2 changed files with 139 additions and 0 deletions

68
FAQ.md
View File

@@ -70,6 +70,74 @@ if __name__ == "__main__":
ButtonApp().run()
```
If you use the above on multiple widgets, you'll find they appear to
"left-align" in the center of the screen, like this:
```
+-----+
| |
+-----+
+---------+
| |
+---------+
+---------------+
| |
+---------------+
```
If you want them more like this:
```
+-----+
| |
+-----+
+---------+
| |
+---------+
+---------------+
| |
+---------------+
```
the best approach is to wrap each widget in a container that individually
centers it. For example:
```python
from textual.app import App, ComposeResult
from textual.containers import Container
from textual.widgets import Button
class Center( Container ):
DEFAULT_CSS = """
Center {
height: auto;
width: 100%;
align: center middle;
}
"""
class ButtonApp(App):
CSS = """
Screen {
align: center middle;
}
"""
def compose(self) -> ComposeResult:
yield Center(Button("PUSH ME!"))
yield Center(Button("AND ME!"))
yield Center(Button("ALSO PLEASE PUSH ME!"))
yield Center(Button("HEY ME ALSO!!"))
if __name__ == "__main__":
ButtonApp().run()
```
<a name="how-do-i-pass-arguments-to-an-app"></a>
## How do I pass arguments to an app?

View File

@@ -2,8 +2,11 @@
title: "How do I center a widget in a screen?"
alt_titles:
- "centre a widget"
- "centre a widgets"
- "center a control"
- "centre a control"
- "center controls"
- "centre controls"
---
To center a widget within a container use
@@ -32,3 +35,71 @@ class ButtonApp(App):
if __name__ == "__main__":
ButtonApp().run()
```
If you use the above on multiple widgets, you'll find they appear to
"left-align" in the center of the screen, like this:
```
+-----+
| |
+-----+
+---------+
| |
+---------+
+---------------+
| |
+---------------+
```
If you want them more like this:
```
+-----+
| |
+-----+
+---------+
| |
+---------+
+---------------+
| |
+---------------+
```
the best approach is to wrap each widget in a container that individually
centers it. For example:
```python
from textual.app import App, ComposeResult
from textual.containers import Container
from textual.widgets import Button
class Center( Container ):
DEFAULT_CSS = """
Center {
height: auto;
width: 100%;
align: center middle;
}
"""
class ButtonApp(App):
CSS = """
Screen {
align: center middle;
}
"""
def compose(self) -> ComposeResult:
yield Center(Button("PUSH ME!"))
yield Center(Button("AND ME!"))
yield Center(Button("ALSO PLEASE PUSH ME!"))
yield Center(Button("HEY ME ALSO!!"))
if __name__ == "__main__":
ButtonApp().run()
```