How to do it...

By adding args=[8] to the thread constructor and modifying the targeted method to expect arguments, we can pass arguments to the threaded methods. The parameter to args has to be a sequence, so we will wrap our number in a Python list:

    def method_in_a_thread(self, num_of_loops=10):
print('Hi, how are you?')
for idx in range(num_of_loops):
sleep(5)
self.scrol.insert(tk.INSERT, str(idx) + 'n')

In the following code, run_thread is a local variable, which we only access within the scope of the method inside which we created run_thread:

    # Running methods in Threads 
def create_thread(self):
run_thread = Thread(target=self.method_in_a_thread, args=[8])
run_thread.start()

By turning the local variable into a member, we can then check if the thread is still running by calling isAlive on it from another method:

    # Running methods in Threads 
def create_thread(self):
self.run_thread = Thread(target=self.method_in_a_thread, args=
[8])
self.run_thread.start()
print(self.run_thread)
print('createThread():', self.run_thread.isAlive())

In the preceding code, we have elevated our local run_thread variable to a member of our class. This enables us to access the self.run_thread variable from any method in our class.

It is achieved like this:

    def method_in_a_thread(self, num_of_loops=10): 
for idx in range(num_of_loops):
sleep(1)
self.scrol.insert(tk.INSERT, str(idx) + 'n')
sleep(1)
print('method_in_a_thread():', self.run_thread.isAlive())

When we click the button and then exit the GUI, we can see that the print statements in the create_thread method were printed, but we do not see the second print statement from method_in_a_thread.

Consider the following output:

Instead of the preceding output, we get the following Runtime Error:

Threads are expected to finish their assigned task, so when we close the GUI while the thread has not completed, Python tells us that the thread we started is not in the main event loop.

We can solve this by turning the thread into a daemon, which will then execute as a background task.

What this gives us is that as soon as we close our GUI, which is our main thread starting other threads, the daemon threads will cleanly exit.

We can do this by calling the setDaemon(True) method on the thread before we start the thread:

    # Running methods in Threads 
def create_thread(self):
self.run_thread = Thread(target=self.method_in_a_thread, args=
[8])
self.run_thread.setDaemon(True)
self.run_thread.start()
print(self.run_thread)

When we now click the button and exit our GUI while the thread has not yet completed its assigned task, we no longer get any errors:

GUI_multiple_threads_stopping_a_thread.py

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.51.36