我已经在开发一个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()
我知道这是一个老问题,但我已经找到了一个方法,为其他人写tkinter。在
我已经在开发一个tkinter应用程序一段时间了,我决定要处理tkinter对象,你绝对需要一个单独的线程。虽然显然不赞成通过
mainloop()
方法之外的其他方法来处理tkinter对象,但它对我来说效果很好。我从未遇到过main thread is not in main loop
错误,也从未遇到过无法正确更新的对象。在我编辑了科里·戈德伯格的代码,让它正常工作。以下是我得到的(评论中的一些解释)。在
我添加了
if __name__=='__main__':
,因为我觉得它更好地定义了范围。在顺便说一句,我发现运行
while 1:
的线程会使我的CPU在某个线程的使用率达到20-30%。通过导入time
并使用time.sleep(0.05)
来显著降低CPU使用率,很容易解决这个问题。在在Win8.1、python3.5.0上测试。在
你试过ttk的确定进度条吗?你只需连续滚动滚动条就可以完成进度。在
例如:
相关问题 更多 >
编程相关推荐