我怎样才能有一个ttk.进度条函数完成时调用它(Python)?

2024-04-26 05:33:05 发布

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

我正在尝试让ttk progressbar调用一个函数,该函数添加到Tkinter窗口中显示的值。我当前有一个函数,它在progressbar开始时被调用:

def bar1_addVal():
     global userMoney
     userMoney += progBar1_values.value
     moneyLabel["text"] = ('$' + str(userMoney))
     canvas1.after((progBar1_values.duration*100), bar1_addVal)
     return

但我似乎无法获得progressbar完成每个迭代所需的确切时间。有没有办法让progressbar在每次完成时调用函数?你知道吗


Tags: 函数textvaluetkinterdefglobalvaluesttk
1条回答
网友
1楼 · 发布于 2024-04-26 05:33:05

可以使用threading检查循环中的变量。这样就不会中断主循环。
我举了一个小例子:

import threading, time
from ttk import Progressbar, Frame
from Tkinter import IntVar, Tk


root = Tk()


class Progress:

    val = IntVar()
    ft = Frame()
    ft.pack(expand=True)
    kill_threads = False  # variable to see if threads should be killed

    def __init__(self):
        self.pb = Progressbar(self.ft, orient="horizontal", mode="determinate", variable=self.val)
        self.pb.pack(expand=True)
        self.pb.start(50)

        threading.Thread(target=self.check_progress).start()


    def check_progress(self):
        while True:
            if self.kill_threads:  # if window is closed
                return             # return out of thread
            val = self.val.get()
            print(val)
            if val > 97:
                self.finish()
                return
            time.sleep(0.1)

    def finish(self):
        self.ft.pack_forget()
        print("Finish!")


progressbar = Progress()


def on_closing():       # function run when closing
    progressbar.kill_threads = True  # set the kill_thread attribute to tru
    time.sleep(0.1)  # wait to make sure that the loop reached the if statement
    root.destroy()   # then destroy the window

root.protocol("WM_DELETE_WINDOW", on_closing) # bind a function to close button

root.mainloop()

编辑:更新答案,在关闭窗口前结束线程。你知道吗

相关问题 更多 >