Tkinter:持续时间不确定的 ProgressBar [英] Tkinter: ProgressBar with indeterminate duration

查看:74
本文介绍了Tkinter:持续时间不确定的 ProgressBar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Tkinter 中实现一个满足以下要求的进度条:

I would like to implement a progress bar in Tkinter which fulfills the following requirements:

  • 进度条是主窗口中唯一的元素
  • 无需按任何按钮即可通过启动命令启动
  • 可以等待未知持续时间的任务完成
  • 只要任务没有完成,进度条的指示器就会一直移动
  • 它可以通过停止命令关闭而无需按下任何停止栏

到目前为止,我有以下代码:

So far, I have the following code:

import Tkinter
import ttk
import time

def task(root):
    root.mainloop()

root = Tkinter.Tk()
ft = ttk.Frame()
ft.pack(expand=True, fill=Tkinter.BOTH, side=Tkinter.TOP)
pb_hD = ttk.Progressbar(ft, orient='horizontal', mode='indeterminate')
pb_hD.pack(expand=True, fill=Tkinter.BOTH, side=Tkinter.TOP)
pb_hD.start(50)
root.after(0,task(root))
time.sleep(5) # to be replaced by process of unknown duration
root.destroy()

这里,问题是5s结束后进度条没有停止.

Here, the problem is that the progress bar does not stop after the 5s are over.

有人能帮我找出错误吗?

Could anybody help me finding the mistake?

推荐答案

一旦主循环处于活动状态,脚本不会移动到下一行,直到根被销毁.可能还有其他方法可以做到这一点,但我更喜欢使用线程来做到这一点.

Once the mainloop is active, the script wont move to the next line until the root is destroyed. There could be other ways to do this, but I would prefer doing it using threads.

像这样,

import Tkinter
import ttk
import time
import threading

#Define your Progress Bar function, 
def task(root):
    ft = ttk.Frame()
    ft.pack(expand=True, fill=Tkinter.BOTH, side=Tkinter.TOP)
    pb_hD = ttk.Progressbar(ft, orient='horizontal', mode='indeterminate')
    pb_hD.pack(expand=True, fill=Tkinter.BOTH, side=Tkinter.TOP)
    pb_hD.start(50)
    root.mainloop()

# Define the process of unknown duration with root as one of the input And once done, add root.quit() at the end.
def process_of_unknown_duration(root):
    time.sleep(5)
    print 'Done'
    root.destroy()

# Now define our Main Functions, which will first define root, then call for call for "task(root)" --- that's your progressbar, and then call for thread1 simultaneously which will  execute your process_of_unknown_duration and at the end destroy/quit the root.

def Main():
    root = Tkinter.Tk()
    t1=threading.Thread(target=process_of_unknown_duration, args=(root,))
    t1.start()
    task(root)  # This will block while the mainloop runs
    t1.join()

#Now just run the functions by calling our Main() function,
if __name__ == '__main__':
    Main()

如果有帮助,请告诉我.

Let me know if that helps.

这篇关于Tkinter:持续时间不确定的 ProgressBar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆