[英]How can I have a ttk.progressbar call a function when it is completed (Python)?
我正在嘗試讓ttk進度欄調用一個添加到Tkinter窗口中顯示的值的函數。 我目前有一個在進度條開始的同時調用的函數:
def bar1_addVal():
global userMoney
userMoney += progBar1_values.value
moneyLabel["text"] = ('$' + str(userMoney))
canvas1.after((progBar1_values.duration*100), bar1_addVal)
return
但我似乎無法獲得進度條完成每次迭代所需的確切時間。 有沒有一種方法可以使進度欄每次完成時都調用一個函數?
您可以使用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()
編輯:更新了答案,以在關閉窗口之前結束線程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.