2014-06-20 242 views
2

我一直在试图在python tkinter gui中设置一个进度条来显示进程正在运行。这个过程很漫长,我无法真正衡量进度,所以我需要使用不确定的进度条。但是,我真的不喜欢tTk不确定进度条的风格来回跳动。我想要一个跨越栏一遍遍滚动,有点像这个图像在Tkinter中滚动进度条

enter image description here

这可能与Tkinter的?

回答

1

你有没有试过ttk的determinate Progressbar?您可以使连续滚动条进度。

例如:

#!/usr/bin/env python3 

import tkinter 
import tkinter.ttk as ttk 

root = tkinter.Tk() 
frame = ttk.Frame() 
pb = ttk.Progressbar(frame, length=300, mode='determinate') 
frame.pack() 
pb.pack() 
pb.start(25) 
root.mainloop() 
+1

有没有一种方法可以让它不是一次又一次地填满酒吧的100%? – drew01886

0

我知道它的一个老问题,但我已经找到了一种方法来为别人写的Tkinter做到这一点。

我一直在做一个tkinter应用程序,现在已经确定要处理tkinter对象,你绝对需要一个单独的线程。尽管通过mainloop()方法处理tkinter物体显然是不被接受的,但它对我来说一直很好。我从来没有遇到过main thread is not in main loop错误,也从未遇到过没有正确更新的对象。

我编辑了科里戈德堡的代码,并得到它的工作。这是我得到的(评论中的一些解释)。

import tkinter 
import tkinter.ttk as ttk 
import threading 

def mainProgram(): # secure the main program initialization in its own def 
    root = tkinter.Tk() 
    frame = ttk.Frame() 
    # You need to use indeterminate mode to achieve this 
    pb = ttk.Progressbar(frame, length=300, mode='indeterminate') 
    frame.pack() 
    pb.pack() 

    # Create a thread for monitoring loading bar 
    # Note the passing of the loading bar as an argument 
    barThread = threading.Thread(target=keepLooping, args=(pb,)) 
    # set thread as daemon (thread will die if parent is killed) 
    barThread.daemon=True 
    # Start thread, could also use root.after(50, barThread.start()) if desired 
    barThread.start() 

    pb.start(25) 
    root.mainloop() 

def keepLooping(bar): 
    # Runs thread continuously (till parent dies due to daemon or is killed manually) 
    while 1: 
     """ 
     Here's the tricky part. 
     The loading bar's position (for any length) is between 0 and 100. 
     Its position is calculated as position = value % 100.  
     Resetting bar['value'] to 0 causes it to return to position 0, 
     but naturally the bar would keep incrementing forever till it dies. 
     It works, but is a bit unnatural. 
     """ 
     if bar['value']==100: 
      bar.config(value=0) # could also set it as bar['value']=0  

if __name__=='__main__': 
    mainProgram()  

我已经加了if __name__=='__main__':,因为我觉得它定义的范围好一点。

作为一个便笺,我发现使用while 1:运行线程会使我的CPU在大约20-30%的使用率下特别适用于该线程。通过导入time并使用time.sleep(0.05)可以轻松解决此问题,从而显着降低CPU使用率。

测试Win8.1,Python 3.5.0。