如何在完成后调用函数ttk.progressbar(Python)?

问题描述 投票:1回答:1

我试图让ttk进度条调用一个函数,该函数添加到Tkinter窗口中显示的值。我目前有一个在进度条开始的同时调用的函数:

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

但我似乎无法获得进度条完成每次迭代所需的确切时间。有没有办法让进度条每次完成时调用一个函数?

python tkinter ttk
1个回答
0
投票

您可以使用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()

编辑:更新了答案,在关闭窗口之前结束线程。

© www.soinside.com 2019 - 2024. All rights reserved.