【问题标题】:Tkinter: ProgressBar with indeterminate durationTkinter:具有不确定持续时间的 ProgressBar
【发布时间】:2014-10-01 20:29:18
【问题描述】:

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

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

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

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结束后没有停止。

谁能帮我找出错误?

【问题讨论】:

    标签: python python-2.7 tkinter progress-bar ttk


    【解决方案1】:

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

    类似的,

    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()
    

    如果有帮助,请告诉我。

    【讨论】:

    • 是的,这正是我需要的。非常感谢!就我而言,我不得不将root.quit 替换为root.destroy()。否则脚本没有正确停止。最后一个问题:是否可以在最后(状态栏停止时)自动关闭整个主窗口?
    • 太好了,我很高兴能帮上忙。 ...现在通过“关闭完整的主窗口”您指的是哪些窗口?此代码只有 TKinter-root 窗口。还有其他窗户吗?
    • @Rickson1982 在这种情况下 sys.exit() 或 quit() 没有帮助吗?我们可以在函数 process_of_unkown_duration(root) 的 root.quit() 下添加它。这有帮助吗?
    • 状态栏会被整合到主程序中,sys.exit()也会关闭主程序。现在唯一的问题是上面的代码打开了一个新的 Tkinter 窗口,其中包含状态栏,在状态栏停止后不会关闭。代码本身运行没有错误。
    • 我不明白。解决方案非常简单。但我需要你的帮助才能更好地理解。只有3个功能。 1)ProgressBar,2)process_of_unkown_duration,3)销毁Progressbar。 .... 或者还有第四个功能吗?不管是什么情况。您希望何时执行 sys.exit()?进度条关闭后立即?或者等待另一个函数执行,然后执行 sys.exit()?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-15
    相关资源
    最近更新 更多