![](/img/trans.png)
[英]Progressbar (ttk.Progressbar) with python in tkinter not showing
[英]Python, Tkinter - ttk.Progressbar in a separate thread
我对此进行了很多搜索,但仍然找不到我想要的东西。 我想这是一个经典的问题,但我仍然无法弄清楚。
我有这个Python / Tkinter代码。 该代码通过使用os.system(cmd)
进行os.system(cmd)
调用来启动一个os.system(cmd)
大量CPU的进程。 我想要一个进度条(摆动一个,而不是渐进式),向用户显示实际发生的事情。 我想我只需要在调用os.system
之前先启动包含进度条的线程,然后在进度条线程运行时调用os.system
,关闭进度条线程并销毁关联的Toplevel()
。
我的意思是说,Python非常灵活,是否可以轻松完成此操作? 我知道从另一个线程中杀死一个线程是不安全的(由于数据共享),但是据我所知,这两个线程不共享任何数据。
是否可以像这样去:
progressbar_thread.start()
os.system(...)
progressbar_thread.kill()
如果那是不可能的,我仍然不明白如何在两个线程之间传递“信号”变量。
谢谢,
安德里亚
在这种情况下,您不需要线程。 只需使用subprocess.Popen
启动子进程即可。
要在进程结束时通知GUI,可以使用widget.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()
这是一个完整的示例 。
这是您所追求的类型吗?
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.