Python 在Tkinter中滚动进度条
我一直在尝试在PythonTkinterGUI中设置一个进度条,显示进程正在运行。这个过程很长,我没有办法真正衡量进度,所以我需要使用一个不确定的进度条。然而,我真的不喜欢ttk不确定进度条来回反弹的风格。我想要一个能在条上反复滚动的,有点像这张图片Python 在Tkinter中滚动进度条,python,tkinter,progress-bar,ttk,Python,Tkinter,Progress Bar,Ttk,我一直在尝试在PythonTkinterGUI中设置一个进度条,显示进程正在运行。这个过程很长,我没有办法真正衡量进度,所以我需要使用一个不确定的进度条。然而,我真的不喜欢ttk不确定进度条来回反弹的风格。我想要一个能在条上反复滚动的,有点像这张图片 tkinter是否可以实现这一点?您是否尝试过ttk的determinate Progressbar?您只需连续滚动条即可取得进展 例如: #!/usr/bin/env python3 import tkinter import tkinter
tkinter是否可以实现这一点?您是否尝试过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()
我知道这是一个古老的问题,但我已经找到了一种方法来为其他写tkinter的人做到这一点 我已经在tkinter应用程序上工作了一段时间,并且已经确定要处理tkinter对象,您绝对需要一个单独的线程。虽然人们显然不赞成通过
mainloop()
方法以外的方法来处理tkinter对象,但它对我来说一直运行良好。我从未遇到过主线程不在主循环中的错误,也从未遇到过更新不正确的对象
我编辑了Corey Goldberg的代码,并使其正常工作。以下是我得到的(评论中的一些解释)
我添加了if\uuuuuu name\uuuu==''\uuuuu main\uuuu':
,因为我觉得它更好地定义了范围
作为补充说明,我发现运行带有而1:
的线程将使CPU的使用率达到20-30%。通过导入time
并使用time.sleep(0.05)
可以轻松解决此问题,从而显著降低CPU使用率
在Win8.1、Python3.5.0上测试。有没有办法让它不只是一次又一次地填满100%的栏?
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()