Tkinter:调用函数时更新进度条 [英] Tkinter: Updating progressbar when a function is called
问题描述
想象下面的简单例子:
def doNothing():
sleep(0.5)
barVar.set(10)
sleep(0.5)
barVar.set(20)
sleep(0.5)
barVar.set(30)
mainWindow = Tk()
barVar = DoubleVar()
barVar.set(0)
bar = Progressbar(mainWindow, length=200, style='black.Horizontal.TProgressbar', variable=barVar, mode='determinate')
bar.grid(row=1, column=0)
button= Button(mainWindow, text='Click', command=doNothing)
button.grid(row=0, column=0)
mainWindow.mainloop()
我得到了什么 当我运行这个时,点击按钮时进度条已经在 30%,我面前没有进度.如附件:
What I get when I run this, the progressbar is already at 30% when clicking the button, no progress in front of me. Like attached:
我需要什么: 我可以看到我面前的进度(不挂然后突然30%)
What I need: I can see the progress in front of me (not hanging then suddenly 30%)
更新:我根据@Bernhard 的回答更新了代码,但我仍然看不到我面前的进度.等了 1.5 秒后突然跳了 30%
Update: I upadted the code according to @Bernhard answer, but still I can not see the progress in front of me. Just a sudden jump of 30% after waiting 1.5 sec
第二次更新:我在这里仅使用 sleep 来模拟需要时间的过程,例如通过 ssh 连接并获取一些信息.
Seocnd Update: I'm only using sleep here as a simulation for a process that takes time, like connecting over ssh and grabing some info.
推荐答案
我想我找到了解决方案.
I think I find the solution.
只需在每个进度后添加 mainWindow.update()
即可.所以最终的代码是:
simply add mainWindow.update()
after each progress. So the final code would be:
def doNothing():
sleep(0.5)
barVar.set(10)
mainWindow.update()
sleep(0.5)
barVar.set(20)
mainWindow.update()
sleep(0.5)
barVar.set(30)
mainWindow.update()
这篇关于Tkinter:调用函数时更新进度条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!