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()
添加回答
举报
