Python,Tkinter-ttk.Progressbar在单独的线程中
我在谷歌上搜索了很多,但我仍然没有找到我要找的东西。 我想这是个经典的问题,但我还是搞不懂 我有这个Python/Tkinter代码。该代码通过使用Python,Tkinter-ttk.Progressbar在单独的线程中,python,multithreading,tkinter,Python,Multithreading,Tkinter,我在谷歌上搜索了很多,但我仍然没有找到我要找的东西。 我想这是个经典的问题,但我还是搞不懂 我有这个Python/Tkinter代码。该代码通过使用os.system(cmd)简单地调用它来启动一个相当CPU密集的进程。我想要一个进度条(摆动的,不是渐进的),它向用户显示实际发生的事情。 我想我只需要在调用os.system之前启动包含进度条的线程,然后在进度条线程运行时调用os.system,关闭进度条线程并销毁associateToplevel() 我的意思是,Python非常灵活,有没有可
os.system(cmd)
简单地调用它来启动一个相当CPU密集的进程。我想要一个进度条(摆动的,不是渐进的),它向用户显示实际发生的事情。
我想我只需要在调用os.system
之前启动包含进度条的线程,然后在进度条线程运行时调用os.system
,关闭进度条线程并销毁associateToplevel()
我的意思是,Python非常灵活,有没有可能不费吹灰之力就能做到这一点?
我知道从另一个线程杀死一个线程是不安全的(由于数据共享),但据我所知,这两个线程不共享任何数据
可以这样走吗:
progressbar_thread.start()
os.system(...)
progressbar_thread.kill()
如果不可能,我仍然不知道如何在两个线程之间传递“信号”变量
谢谢,
安德里亚这就是你想要的那种东西吗
from Tkinter import *
import ttk, threading
class progress():
def __init__(self, parent):
toplevel = Toplevel(tk)
self.progressbar = ttk.Progressbar(toplevel, orient = HORIZONTAL, mode = 'indeterminate')
self.progressbar.pack()
self.t = threading.Thread()
self.t.__init__(target = self.progressbar.start, args = ())
self.t.start()
#if self.t.isAlive() == True:
# print 'worked'
def end(self):
if self.t.isAlive() == False:
self.progressbar.stop()
self.t.join()
def printmsg():
print 'proof a new thread is running'
tk = Tk()
new = progress(tk)
but1 = ttk.Button(tk, text= 'stop', command= new.end)
but2 = ttk.Button(tk, text = 'test', command= printmsg)
but1.pack()
but2.pack()
tk.mainloop()
在这种情况下,您不需要线程。只需使用启动子流程 要在进程结束时通知GUI,可以使用
小部件实现轮询。after()
方法:
process = Popen(['/path/to/command', 'arg1', 'arg2', 'etc'])
progressbar.start()
def poller():
if process.poll() is None: # process is still running
progressbar.after(delay, poller) # continue polling
else:
progressbar.stop() # process ended; stop progress bar
delay = 100 # milliseconds
progressbar.after(delay, poller) # call poller() in `delay` milliseconds
如果要在不等待的情况下手动停止进程:
if process.poll() is None: # process is still running
process.terminate()
# kill process in a couple of seconds if it is not terminated
progressbar.after(2000, kill_process, process)
def kill_process(process):
if process.poll() is None:
process.kill()
process.wait()
这里有一个。progressbar.start()
会立即返回,因此线程在这里是完全无用的(它一开始就结束)printmsg
不能证明线程正在运行。您不应该直接调用\uuuuu init\uuuu
;语法是:Thread(target=some\u func,args=func\u args)
。