2017-09-02 89 views
1

我已经创建了一个进度条,它在从另一个函数中获取一个百分比后自动更新,但是我有问题让它像这样跟踪############。相反,它只是将“#”向右移至100%。以下是我的代码。之所以这样,是因为我需要百分比来自外部,这样代码才能重用。请帮帮我。python curses中的进度条

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

回答

0

你可以切换pos乘以display #

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

感谢您解决我的问题!被困了几个小时!加载完成后,我还有一个问题就消失了。可能你知道一种让它留下来的方法吗? – answerSeeker

+0

它留在我的终端,你在用什么外壳? – PRMoureu

+0

这是gnome终端 – answerSeeker

2

的问题是,你叫newwin()每一次,丢弃旧win,并在同一个地方一个新的替换它。那个新窗口只会添加一个字符,背景是空白的,所以你看到一个前进光标而不是一个条。

一个可能的解决方案:

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

(请注意,除了endwin()呼叫的终端恢复到正常模式)

至于留在该计划完成后屏幕上,这是诅咒的范围之外。你不能真正依靠curses和stdio之间的任何交互,抱歉。