[英]Scrolling Progress Bar in Tkinter
我一直在尝试在python tkinter gui中设置一个进度条,表明进程正在运行。 这个过程很长,我无法真正衡量进度,所以我需要使用一个不确定的进度条。 但是,我真的不喜欢ttk不确定进度条的样式来回反弹。 我想要一个一遍又一遍地滚过酒吧的那个,有点像这个图像
这可能与tkinter有关吗?
你试过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()
我知道这是一个古老的问题,但我找到了一种方法来为其他任何人写tkinter。
我现在一直在研究tkinter应用程序并确定要处理tkinter对象,你绝对需要一个单独的线程。 虽然通过除了mainloop()
方法以外的其他东西处理mainloop()
对象显然mainloop()
,但它一直很适合我。 我从来没有一个main thread is not in main loop
错误,从未经历过没有正确更新的对象。
我编辑了Corey Goldberg的代码并使其正常工作。 这是我得到的(评论中的一些解释)。
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:
运行线程while 1:
特别是对于那个线程,我的CPU使用率约为20-30%。 通过导入time
和使用time.sleep(0.05)
可以轻松解决此问题,从而显着降低CPU使用率。
在Win8.1,Python 3.5.0上测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.