<p>这里有一个很有希望的简单的多处理方法,将为您工作。我们将有三个主要功能。第一个是一个示例循环,您可以将处理放在其中。我在函数中包含了参数,以向您展示在使用多处理时可以传递arg和kwargs。在</p>
<pre class="lang-py prettyprint-override"><code>def loop(a, b, c, d):
# Will just sleep for 3 seconds.. simulates whatever processing you do.
time.sleep(3)
return
</code></pre>
<p>接下来是一个函数,我们将用来对多处理进程进行排队。在</p>
^{pr2}$
<p>你可能会对你的整个执行过程感兴趣。例如,有时需要在运行命令时禁用某些按钮。在</p>
<pre class="lang-py prettyprint-override"><code>def check_status(p):
""" p is the multiprocessing.Process object """
if p.is_alive(): # Then the process is still running
label.config(text = "MP Running")
mp_button.config(state = "disabled")
not_mp_button.config(state = "disabled")
root.after(200, lambda p=p: check_status(p)) # After 200 ms, it will check the status again.
else:
label.config(text = "MP Not Running")
mp_button.config(state = "normal")
not_mp_button.config(state = "normal")
return
</code></pre>
<p>把这些都放在一个片段里:</p>
<pre class="lang-py prettyprint-override"><code>import tkinter as tk
import multiprocessing
import time
def loop(a, b, c, d):
# Will just sleep for 3 seconds.. simulates whatever processing you do.
time.sleep(3)
return
def queue_loop():
p = multiprocessing.Process(target = loop,
args = (1, 2),
kwargs = {"c": 3, "d": 4})
# You can pass args and kwargs to the target function like that
# Note that the process isn't started yet. You call p.start() to activate it.
p.start()
check_status(p) # This is the next function we'll define.
return
def check_status(p):
""" p is the multiprocessing.Process object """
if p.is_alive(): # Then the process is still running
label.config(text = "MP Running")
mp_button.config(state = "disabled")
not_mp_button.config(state = "disabled")
root.after(200, lambda p=p: check_status(p)) # After 200 ms, it will check the status again.
else:
label.config(text = "MP Not Running")
mp_button.config(state = "normal")
not_mp_button.config(state = "normal")
return
if __name__ == "__main__":
root = tk.Tk()
mp_button = tk.Button(master = root, text = "Using MP", command = queue_loop)
mp_button.pack()
label = tk.Label(master = root, text = "MP Not Running")
label.pack()
not_mp_button = tk.Button(master = root, text = "Not MP", command = lambda: loop(1,2,3,4))
not_mp_button.pack()
root.mainloop()
</code></pre>
<p>结果是,当您单击“Using MP”按钮时,命令按钮将被禁用,并且该过程将在不冻结用户界面的情况下启动。单击“notmp”按钮将启动类似“normal”的函数,并将冻结您在自己的代码中注意到的UI。在</p>