如何添加不确定功能的tkinter进度条

How to add tkinter progress bar indeterminate with function

from tkinter import *
from tkinter import ttk

def DOTEST_GUI():
    GUI = Tk()
    w = 1920
    h = 1080
    ws = GUI.winfo_screenwidth()
    hs = GUI.winfo_screenheight()
    x = (ws/2) - (w/2)
    y = (hs/2) - (h/2)
    GUI.geometry(f'{w}x{h}+{x:.0f}+{y:.0f}')

    def start_p():
        progress.start(5)

    def stop_P():
        progress.stop()

    def print_cf(event = None):
        import time
        print('s')
        start_p()
        time.sleep(5)
        stop_P()

    B_TEST = ttk.Button(GUI, text = "test", width = 15, command = print_cf)
    B_TEST.pack()

    progress = ttk.Progressbar(GUI, orient = HORIZONTAL, length = 100, mode = 'indeterminate')
    progress.pack(pady = 10)

    GUI.bind("<Return>", print_cf)

    GUI.focus()
    GUI.mainloop()

DOTEST_GUI()

遵循此代码进度条不正确 运行。

我尝试删除 stop_P(),它在 time.sleep(5) 的 5 秒后起作用。

我希望它开始 运行 进度 5 秒,直到 stop_P() 代码。

如果你想 运行 一个 Progressbar 一段时间然后停止,你可以做这样的事情。合并print_cf函数启动和停止进度,设置范围为5,中间休眠1秒,然后停止Progressbar。将它放在一个线程上会让你做一些比休眠一秒钟并打印一些东西更耗时的事情。

from tkinter import *
from tkinter import ttk
import time
import threading



                    
def DOTEST_GUI():
    GUI = Tk()
    w = 1920
    h = 1080
    ws = GUI.winfo_screenwidth()
    hs = GUI.winfo_screenheight()
    x = (ws/2) - (w/2)
    y = (hs/2) - (h/2)
    GUI.geometry(f'{w}x{h}+{x:.0f}+{y:.0f}')


    def run_thread():
        execute_thread = threading.Thread(target=print_cf)
        execute_thread.start()

        
    def print_cf(event = None):
        progress.start()
        print('s')
        for i in range(5):
            print(i)
            time.sleep(1)
            if i ==4:
                progress.stop()


    B_TEST = ttk.Button(GUI, text = "test", width = 15, command = run_thread)
    B_TEST.pack()

    progress = ttk.Progressbar(GUI, orient = HORIZONTAL, length = 100, mode = 'indeterminate')
    progress.pack(pady = 10)

    GUI.bind("<Return>", print_cf)

    GUI.focus()
    GUI.mainloop()
        

DOTEST_GUI()