在Tkin中滚动进度条

2024-06-16 17:56:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试在pythonttkintergui中设置一个进度条,显示一个进程正在运行。这个过程很长,我没有办法真正衡量进度,所以我需要使用一个不确定的进度条。然而,我真的不喜欢ttk不确定进度条的风格,它来回地跳跃。我想要一个能在吧台上反复滚动的,像这张图片

enter image description here

tkinter有可能吗?在


Tags: 进度条进程风格tkinter过程图片ttk办法
2条回答

我知道这是一个老问题,但我已经找到了一个方法,为其他人写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、python3.5.0上测试。在

你试过ttk的确定进度条吗?你只需连续滚动滚动条就可以完成进度。在

例如:

#!/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()

相关问题 更多 >