简体   繁体   English

python curses中的进度栏

[英]Progress bar in python curses

I have created a progress bar which updates itself after getting a percentage from another function but I'm having issues getting it to trail like this ############. 我创建了一个进度条,该进度条在从另一个函数中获取一定百分比后会进行自我更新,但是我遇到了使它像这样############ Instead, it just move the '#' to the right until 100% is reached. 相反,它只是将“#”向右移动,直到达到100%。 Below is my code. 下面是我的代码。 The reason why it's this way is because I need the percentage to come externally so that the code can be reusable. 之所以采用这种方式,是因为我需要从外部获取该百分比,以便代码可以重用。 please help me. 请帮我。

import curses
import time

curses.initscr()

def percentage():
    loading = 0
    while loading < 100:
        loading += 1
        time.sleep(0.03)
        update_progress(loading)


def update_progress(progress):
    win = curses.newwin(3, 32, 3, 30)
    win.border(0)
    rangex = (30 / float(100)) * progress
    pos = int(rangex)
    display = '#'
    if pos != 0:
        win.addstr(1, pos, "{}".format(display))
        win.refresh()

percentage()

The problem is that you call newwin() every time, discarding the old win and replacing it with a new one in the same place. 问题是您每次都调用newwin() ,丢弃旧的win ,然后在同一位置替换为新的win That new window only gets one character added to it, with the background being blank, so you see an advancing cursor instead of a bar. 该新窗口仅添加了一个字符,背景为空白,因此您看到的是前进的光标而不是条。

One possible solution: 一种可能的解决方案:

import curses
import time

curses.initscr()

def percentage():
    win = curses.newwin(3, 32, 3, 30)
    win.border(0)
    loading = 0
    while loading < 100:
        loading += 1
        time.sleep(0.03)
        update_progress(win, loading)

def update_progress(win, progress):
    rangex = (30 / float(100)) * progress
    pos = int(rangex)
    display = '#'
    if pos != 0:
        win.addstr(1, pos, "{}".format(display))
        win.refresh()

percentage()

curses.endwin()

(Note the addition of a call to endwin() to restore the terminal to its normal mode.) (请注意,还添加了对endwin()的调用,以将终端恢复为正常模式。)

As far as leaving it onscreen after the program finishes, that's kind of outside the scope of curses. 至于在程序完成后将其显示在屏幕上,那超出了诅咒的范围。 You can't really depend on any interaction between curses and stdio, sorry. 抱歉,您不能真正依赖于curses和stdio之间的任何交互。

you can just switch the pos to multiply the display # : 您只需切换pos以乘以display #

if pos != 0:
    win.addstr(1, 1, "{}".format(display*pos))
    win.refresh()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM