Tkinter:具有不确定持续时间的ProgressBar

2024-05-05 21:24:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在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结束后不会停止

有人能帮我找出错误吗


Tags: 进度条import命令truetasktimetkinterroot
1条回答
网友
1楼 · 发布于 2024-05-05 21:24:45

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

像这样的,

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

如果有帮助,请告诉我

相关问题 更多 >