2017-09-02 100 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之間的任何交互,抱歉。