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

时间:2017-12-16 01:20:25

标签: python tkinter ttk

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

var day = "monday"

// day[0].toUpperCase() returns a new string:
console.log("day[0].toUpperCase() is:", day[0].toUpperCase())

// You can use the substring method to get the rest of the string.
console.log("day.substring(1) is:", day.substring(1));

// Use these two in combination to uppercase the first letter:
console.log("combo:", day[0].toUpperCase() + day.substring(1));

// And save that into a new variable:
var capDay = day[0].toUpperCase() + day.substring(1);

// But note that the orignal string is still unchanged.
console.log("The original is still unchanged. Original:", day);
console.log("But the new variable is different:", capDay);

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

1 个答案:

答案 0 :(得分: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()

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