問題描述
如何在沒有多線程的情況下在 python 中運(yùn)行多個(gè)進(jìn)程?例如考慮以下問題:-
How to run multiple processes in python without multithreading? For example consider the following problem:-
我們必須制作一個(gè) Gui,它有一個(gè)開始按鈕,用于啟動(dòng)一個(gè)函數(shù)(例如,打印所有整數(shù)),還有一個(gè)停止按鈕,這樣點(diǎn)擊它就會(huì)停止函數(shù).
We have to make a Gui,which has a start button which starts a function(say, prints all integers) and there is a stop button, such that clicking it stops the function.
如何在 Tkinter 中做到這一點(diǎn)?
How to do this in Tkinter?
推薦答案
然后您需要將 Button
小部件與啟動(dòng)工作線程的函數(shù)綁定.例如:
Then you need to bind the Button
widget with the function which starts the working thread. For example:
import time
import threading
import Tkinter as tk
class App():
def __init__(self, root):
self.button = tk.Button(root)
self.button.pack()
self._resetbutton()
def _resetbutton(self):
self.running = False
self.button.config(text="Start", command=self.startthread)
def startthread(self):
self.running = True
newthread = threading.Thread(target=self.printints)
newthread.start()
self.button.config(text="Stop", command=self._resetbutton)
def printints(self):
x = 0
while self.running:
print(x)
x += 1
time.sleep(1) # Simulate harder task
使用 self.running
方法,您只能通過更改線程的值來優(yōu)雅地結(jié)束線程.請(qǐng)注意,使用多個(gè)線程可以避免在執(zhí)行 printints
時(shí)阻塞 GUI.
With the self.running
approach, you can end the thread gracefully only by changing its value. Note that the use of multiple threads serves to avoid blocking the GUI while printints
is being executed.
我已閱讀 this previous question,我想您為什么在這里明確要求解決方案沒有多線程.在 Tkinter 中,此解決方案可用于其他線程必須與 GUI 部分通信的場(chǎng)景.例如:在渲染某些圖像時(shí)填充進(jìn)度條.
I have read this previous question and I suppose why you explicitly asked here for a solution without multithreading. In Tkinter this solution can be used in a scenario where the other threads have to communicate with the GUI part. For example: filling a progressbar while some images are being rendered.
但是,正如評(píng)論中所指出的那樣,這種方法對(duì)于僅打印數(shù)字來說太復(fù)雜了.
However, as it has been pointed in the comments, this approach is too complex for just printing numbers.
這里您可以找到很多關(guān)于 Tkinter 的信息和更多示例.
Here you can find a lot of information and more examples about Tkinter.
由于您的新問題已關(guān)閉,我將在此處更改代碼以澄清最后一點(diǎn).
Since your new question has been closed, I'll change the code here to clarify the last point.
這篇關(guān)于Python tkinter 中的多處理的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!