DEV Community

codemee
codemee

Posted on

Python 文字模式程式技巧

文字模式程式雖然受限於無法繪圖, 但是只要善用特別的字元與脫義序列 (escape sequence), 加上 ANSI 序列的輔助, 也可以完成很有趣的應用。

顯示工作中繞圈圈的效果

如果你的程式需要一段時間進行某項工作, 像是下載大的檔案等等等, 最好可以提供明確的提示讓使用者知道, 要做到這件事, 可以依靠盲人符號 的幫助:

⠏⠋⠙⠹⠼⠴⠦⠧
Enter fullscreen mode Exit fullscreen mode

只要在同一位置輪流顯示這些字元, 就可以造成繞圈圈的效果:

import time

# braille = "\u280B\u2819\u2839\u283c\u2834\u2826\u2827\u280f"
braille = "⠏⠋⠙⠹⠼⠴⠦⠧"
hide_cursor = "\033[?25l"
show_cursor = "\033[?25h"
print("     測試等待轉圈圈" + hide_cursor, end='')
for i in range(100):
    for c in braille:
        print("\r" + c, end="")
        time.sleep(0.1)
print(show_cursor)

Enter fullscreen mode Exit fullscreen mode

其中 "\r" 可以讓游標回到行首在同一個地方顯示, 而 hide_cursorshow_cursor 則可以隱藏及顯示游標, 避免與繞圈圈的字元黏在一起影響顯示效果。最後的效果如下:

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more