1 回答

TA貢獻1719條經驗 獲得超6個贊
首先,Tkinter 不支持多線程,所以所有關于 GUI 的代碼都應該在主線程中。所以無法在real_pb().
只要進程正在運行,我會做的是使用一個threading.Event在進程完成時將設置的對象。在 Tkinter mainloop 內部,我會定期輪詢 Event 以了解進程是否完成:
from tkinter import Button, Tk, HORIZONTAL, Toplevel
import time
from tkinter.ttk import Progressbar
import threading
class Main(Tk):
def __init__(self):
super().__init__()
self.btn = Button(self, text='Run', command=self.pb)
self.btn.grid(row=0,column=0)
self.finished = threading.Event() # event used to know if the process is finished
def pb(self):
def check_if_finished():
if self.finished.is_set():
# process is finished, destroy toplevel
window.destroy()
self.btn['state']='normal'
else:
self.after(1000, check_if_finished)
window = Toplevel(root)
window.progress = Progressbar(window, orient=HORIZONTAL,length=100, mode='indeterminate')
window.progress.grid(row=1,column=0)
window.progress.start()
self.btn['state']='disabled'
threading.Thread(target=self.dummyscript).start()
self.after(1000, check_if_finished) # check every second if the process is finished
def dummyscript(self):
self.finished.clear() # unset the event
time.sleep(10) # execute script
print("slept")
self.finished.set() # set the event
root = Main()
root.mainloop()
添加回答
舉報