【问题标题】:How to prevent progress bar animation from writing to multiple lines? [duplicate]如何防止进度条动画写入多行? [复制]
【发布时间】:2021-02-18 20:14:01
【问题描述】:

我有这个代码:

animation = ["[■□□□□□□□□□]", "[■■□□□□□□□□]", "[■■■□□□□□□□]", "[■■■■□□□□□□]",
             "[■■■■■□□□□□]", "[■■■■■■□□□□]", "[■■■■■■■□□□]", "[■■■■■■■■□□]",
             "[■■■■■■■■■□]", "[■■■■■■■■■■]"]

import sys

for i in range(len(animation)):
    time.sleep(0.2)
    sys.stdout.write("\r" + animation[i % len(animation)]+ "\n")
    sys.stdout.flush()

但是动画是这样一个一个的:

[■□□□□□□□□□]

[■■□□□□□□□□]

而不是更换盒子。如何让它看起来像动画?

编辑:我忘了提到我在 pysimpleguy 布局中使用它。不知道它是否重要。

【问题讨论】:

  • 几个问题:你为什么使用sys.stdout而不是print()?为什么不直接迭代动画字符串而不是使用索引和模数?即:for anim in animations:
  • t.generate() 是做什么的?您需要提供一个可运行的minimal reproducible example
  • @martineau t.generate() 制作一个 torrent 文件,这是我想要制作进度条的地方。
  • 由于这与您的问题无关,因此应该将其删除,以便拥有重现问题所需的绝对最少数量的代码。
  • @martineau 完成。

标签: python progress-bar pysimplegui


【解决方案1】:

您可以使用Rich library 制作进度条。

这是一些示例代码。

import time

from rich.progress import Progress

with Progress() as progress:

    task = progress.add_task("[green]Processing...", total=1000)

    while not progress.finished:
        progress.update(task, advance=0.5)
        time.sleep(0.02)

【讨论】:

    【解决方案2】:

    通过使用"\n",您将光标移动到新行,因此下一个"\r" 只是返回到该行的开头。只需删除 "\n" 即可。

    【讨论】:

    • 我添加了“\n”以看起来更漂亮。因为它首先并排显示而不是逐行显示
    • @Cristina 这就是"\r" 的用途,将光标返回到行首。
    • 删除 \n 将不起作用:i.imgur.com/204THIX.png,我忘了提到我在 pysimpleguy 布局中使用它。不知道它是否重要。
    • @Cristina:你的意思是“PySimpleGUI”吗?如果是这样,那么 yes 这很重要。 PySimpleGUI 有一些名为 ProgressBarone_line_progress_meter 的东西 - 查找它们。
    猜你喜欢
    • 1970-01-01
    • 2017-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多