我有一些代码,可以通过telnet Sessions将某些代码推向机器。在此期间(大约30秒(GUI(TKINTER(悬挂,似乎该程序崩溃了。为了解决这个问题,我想使用进度栏。因此,按下"发送"按钮后,它将打开一个新屏幕。到目前为止,一切都很好。现在,我希望一旦完成telnet脚本,进度栏就可以停止。因此,我已经进行了一些研究,我认为我需要使用(多(线程。一旦TelnetThread完成了,ProgressBarthread应该停止,我再次看到主屏幕。
这是脚本Sofar ...
from tkinter import Button, Tk, HORIZONTAL
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)
def pb(self):
def real_pb():
window = tk.Toplevel(root)
window.progress = Progressbar(window, orient=HORIZONTAL,length=100, mode='indeterminate')
window.progress.grid(row=1,column=0)
window.progress.start()
time.sleep(10)#to be changed to thread of telnet session//dummyscript
window.progress.stop()
window.progress.grid_forget()
window.destroy()
self.btn['state']='normal'
self.btn['state']='disabled'
threading.Thread(target=real_pb).start()
def dummyscript():
time.sleep(10)
print("slept")
root = main()
root.mainloop()
如何将time.sleep
更改为DummyScript的长度?
首先,tkinter不支持多线程,因此有关GUI的所有代码都应在主线程中。因此,real_pb()
无法创建TopLevel和ProgressBar。
只要该过程正在运行,我将采取的措施显示该进度键,即在过程完成后使用将设置的threading.Event
对象。在TKInter Mainloop中,我会定期对活动进行调查,以了解该过程是否完成:
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()