我一直在尝试在python tkinter gui中设置一个进度条,表明进程正在运行。这个过程很长,我无法真正衡量进度,所以我需要使用一个不确定的进度条。但是,我真的不喜欢ttk不确定进度条的样式来回反弹。我想要一个一遍又一遍地滚过酒吧的那个,有点像这个图像
这可以用tkinter吗?
答案 0 :(得分:2)
例如:
#!/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 :(得分:0)
我知道这是一个古老的问题,但我找到了一种方法来为其他任何人写tkinter。
我现在一直在研究tkinter应用程序并确定要处理tkinter对象,你绝对需要一个单独的线程。虽然通过mainloop()
方法以外的其他方式处理tkinter对象显然不赞成,但它对我来说效果很好。我从未遇到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:
运行线程会使我的CPU在特定的一个线程中使用大约20-30%的使用率。它可以通过导入time
并使用time.sleep(0.05)
轻松解决,从而显着降低CPU使用率。
在Win8.1,Python 3.5.0上测试。