Как можно вывести текст в центре экрана терминала, используя shutil.get_terminal_size().columns
и shutil.get_terminal_size().lines
?
-
1вывести в строку и добавить пробелов в начало строки (их количество будет (ширина терминала - ширина строки) / 2 )?– pavel29 апр 2016 в 17:30
-
@pavel Я немного поправил. Смотрите на изображение.– CockLobster29 апр 2016 в 17:37
-
ну тогда могу предложить тоже самое, но отступ брать минимальный их всех строк, которые выводить.– pavel29 апр 2016 в 17:45
2 ответа
Если текст уже разбит на строки, то достаточно просто отформатировать:
>>> import shutil
>>> lines = ['String right here', 'And here', 'Here', 'A-a-a-and here']
>>> width = shutil.get_terminal_size().columns
>>> position = (width - max(map(len, lines))) // 2
>>> for line in lines: # left justtified
... print(' '*position + line)
...
String right here
And here
Here
A-a-a-and here
>>> for line in lines: # right justified
... print(line.rjust(width // 2))
...
String right here
And here
Here
A-a-a-and here
>>> for line in lines: # center
... print(line.center(width))
...
String right here
And here
Here
A-a-a-and here
-
А как можно центрировать текст (третий пример) с выравниваем по левому краю? 30 апр 2016 в 12:13
-
-
-
в чём по вашему отличие от изображения в вопросе? Куда текст подвинуть: лево, право, верх, низ?– jfs30 апр 2016 в 12:32
-
сделал так:
nl = (height - max(map(len, textArray))) // 2 + 11;print('\n'*nl)
Всё работает. 30 апр 2016 в 12:36
Если хочется в произвольном месте экрана в терминале печатать, то можно blessings
модуль использовать:
#!/usr/bin/env python
from blessings import Terminal # $ pip install blessings
lines = ['String right here', 'And here', 'Here', 'A-a-a-and here']
term = Terminal()
with term.hidden_cursor(), term.fullscreen():
for i, line in enumerate(lines):
x = (term.width - max(map(len, lines))) // 2
y = (term.height - len(lines)) // 2 + i
with term.location(x, y):
print(term.bold_white_on_black(line))
with term.location(0, term.height - 1):
input('press <Enter> to exit..')
Терминал выглядит так:
String right here And here Here A-a-a-and here press <Enter> to exit..
В этом случае, содержимое терминала на время исполнения программы очищается—при выходе из программы терминал восстанавливается.
Совместно с colorama
модулем, некоторые возможности могут работать также и на Windows.
Для забавы можно asciimatics
модуль попробовать:
#!/usr/bin/env python
from asciimatics.effects import Print # $ pip install asciimatics
from asciimatics.renderers import FigletText, SpeechBubble, Rainbow
from asciimatics.scene import Scene
from asciimatics.screen import Screen
from asciimatics.exceptions import ResizeScreenError
def demo(screen):
lines = ['String right here', 'And here', 'Here', 'A-a-a-and here']
renderers = [Rainbow(screen, FigletText(line, font='small'))
for line in lines]
x = (screen.width - max(r.max_width for r in renderers)) // 2
H = max(r.max_height for r in renderers) - 1 # text height
effects = [Print(screen, renderer,
y=(screen.height - H * len(renderers)) // 2 + i * H, x=x)
for i, renderer in enumerate(renderers)]
effects.append(Print(screen,
SpeechBubble("Press X to exit"),
screen.height - 5,
speed=1, transparent=False,
start_frame=100))
screen.play([Scene(effects, -1)], stop_on_resize=True)
if __name__ == "__main__":
while True:
try:
Screen.wrapper(demo)
except ResizeScreenError:
continue
else:
break
На другие доступные эффекты можно в samples папке посмотреть.