1

I have this code:

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()

But the animation is one by one like this:

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

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

Instead of replacing the boxes. How can I make it look like an animation?

Edit: i forget to mention that i use it inside a pysimpleguy layout. Dont know if it its important.

martineau
  • 119,623
  • 25
  • 170
  • 301
Cristina
  • 35
  • 6
  • Couple questions: why are you using `sys.stdout` over `print()`? Why not simply iterate over the animation strings directly instead of using an index and modulus? I.e.: `for anim in animations:` – ddejohn Feb 18 '21 at 20:23
  • What does `t.generate()` do? You need to provide a runnable [mre]. – martineau Feb 18 '21 at 20:40
  • @martineau the t.generate() makes an torrent file, it is what i want to make a progress bar for. – Cristina Feb 18 '21 at 20:54
  • Since that has nothing to do with your question, it should have been removed in order to have the absolute _minimum_ amount of code necessary to reproduce the problem. – martineau Feb 18 '21 at 21:00
  • @martineau Done. – Cristina Feb 18 '21 at 21:17

2 Answers2

1

You can use the Rich library to make progress bars.

Here is some example code.

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)
Adilius
  • 308
  • 2
  • 10
1

By using "\n" you move the cursor to a new line and hence the next "\r" simply returns to the beginning of that line. Just remove the "\n" and it will work.

a_guest
  • 34,165
  • 12
  • 64
  • 118
  • i added the "\n" to look more beautiful. because it first show side by side instead of line by line – Cristina Feb 18 '21 at 20:53
  • @Cristina Well that's what the `"\r"` is used for, return the cursor to the beginning of the line. – a_guest Feb 18 '21 at 21:04
  • Removing the \n will not work: https://i.imgur.com/204THIX.png, i forget to mention that i use it inside a pysimpleguy layout. Dont know if it its important. – Cristina Feb 18 '21 at 21:19
  • @Cristina: Do you mean "PySimpleGUI"? If so, then ***yes*** it matters a great deal. PySimpleGUI has somethings called `ProgressBar` and `one_line_progress_meter` — look them up. – martineau Feb 19 '21 at 00:09