4
votes

How to run multiple processes in python without multithreading? For example consider the following problem:-

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.

How to do this in Tkinter?

2
when you say "another process" do you literally mean another process -- spawning a .exe or equivalent? Or, when you say "process" do you really mean "some other function"? I find it hard to believe you would have a whole separate process just to print integers. - Bryan Oakley
I meant some other function. - Chandan
@Chandan: terminology is critically important when asking technical questions. There is a huge difference between a process and a function in this context. You should edit your question to reflect that you don't intend to spawn other processes. - Bryan Oakley

2 Answers

4
votes

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

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.

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.

However, as it has been pointed in the comments, this approach is too complex for just printing numbers.

Here you can find a lot of information and more examples about Tkinter.


Edit:

Since your new question has been closed, I'll change the code here to clarify the last point.

0
votes

Did you try to used multiprocessing module? Seems to be the one you're looking for.