Python - 覆盖已在输出中打印的文本

它仅在 PyCharm 中以视觉方式工作


我正在编写一个电梯程序,我尝试像真正的电梯一样制作等待灯动画。但我想在之后打印一些输出,以便您可以在灯光动画开始之前看到整个电梯。


from termcolor import cprint

import time


# this would be user's input

level = 10


# ABOVE PART ELEVATOR

cprint('         ▲  ▼        ', 'yellow')

cprint('    ┏' + ('━' * 13) + '┓')


# LIGHTS

print('    ┃', end='')

for lights in range(1, 11):

    cprint('⦿', 'yellow', end='', flush=True)

    time.sleep(0.5)

print('┃')


# LOWER PART ELEVATOR

print('    ┣━━━━━━╥━━━━━━┫')

print('    ┃      ║      ┃\n' * 5 + '    ┃      ║      ┃')

print('━━━━┗━━━━━━╨━━━━━━┛━━━━')


print(f'\nYou have arrived at floor ', end='')

cprint(level, 'yellow')

所以这是一个像普通程序一样从左到右、从上到下打印的程序。但我希望输出是:


         ▲  ▼        

    ┏━━━━━━━━━━━━━┓

    ┃   #lights   ┃ <- animation appears after the entire elevator

    ┣━━━━━━╥━━━━━━┫

    ┃      ║      ┃

    ┃      ║      ┃

    ┃      ║      ┃

    ┃      ║      ┃

    ┃      ║      ┃

    ┃      ║      ┃

━━━━┗━━━━━━╨━━━━━━┛━━━━


"You have arrived at floor 10" <- this after lights


狐的传说
浏览 172回答 2
2回答

慕田峪9158850

您的代码的问题在于,电梯的下部仅在显示灯光的 for 循环结束后才绘制。您必须在 for 循环内绘制整个电梯,这样电梯就会在灯光更新时显示。注意:为了很好地做到这一点,您应该在 for 循环的每次迭代后始终清除控制台。要执行此操作,您必须先执行此操作from os import system,然后再清除屏幕,就像system("clear")在 Linux 或 Mac 和system("cls")Windows 上执行的操作一样。这是编辑后的代码:from termcolor import cprintimport timefrom os import systemlevel = int(input('Which floor would you like to visit?\n')) + 1light = '⦿'lights = lightfor currentlevel in range(1, level):&nbsp; &nbsp; system('clear')&nbsp;&nbsp; &nbsp; cprint('&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;▲&nbsp; ▼&nbsp; &nbsp; &nbsp; &nbsp; ', 'yellow')&nbsp; &nbsp; cprint('&nbsp; &nbsp; ┏' + ('━' * 13) + '┓')&nbsp; &nbsp; print('&nbsp; &nbsp; ┃', end='')&nbsp; &nbsp; cprint(lights, 'yellow', end='', flush=True)&nbsp; &nbsp; print('┃')&nbsp; &nbsp; print('&nbsp; &nbsp; ┣━━━━━━╥━━━━━━┫')&nbsp; &nbsp; print('&nbsp; &nbsp; ┃&nbsp; &nbsp; &nbsp; ║&nbsp; &nbsp; &nbsp; ┃\n' * 5 + '&nbsp; &nbsp; ┃&nbsp; &nbsp; &nbsp; ║&nbsp; &nbsp; &nbsp; ┃')&nbsp; &nbsp; print('━━━━┗━━━━━━╨━━━━━━┛━━━━')&nbsp; &nbsp; print(f'\nYou have arrived at floor ', end='')&nbsp; &nbsp; cprint(currentlevel, 'yellow')&nbsp; &nbsp; time.sleep(0.5)&nbsp; &nbsp; lights += light干杯!

侃侃尔雅

请注意,它仅适用于本机 Windows 控制台,但不适用于 pycharm 控制台,该控制台打印错误为“不支持重定向”。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python