Ask Your Question
2

What is the method to terminate a thread that includes a blocking function from easygui in python?

asked 2022-05-09 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-07-05 12:00:00 +0000

david gravatar image

One way to terminate a thread that includes a blocking function from easygui in Python is to use a flag variable that is checked regularly within the thread's main loop or function. When the flag is set to a certain value, the thread stops executing its main loop or function and terminates.

Here's an example code snippet that demonstrates this approach:

import threading
import easygui

# Global flag variable
stop_thread = False

def my_thread_function():
    # Loop until the stop_thread flag is set
    while not stop_thread:
        # Call a blocking function from easygui
        result = easygui.ynbox("Do you want to continue?", "Question")
        if result:
            easygui.msgbox("Great!")
        else:
            easygui.msgbox("Okay, goodbye!")

    # If the stop_thread flag is set, the function returns and the thread terminates
    return

# Create and start the thread
my_thread = threading.Thread(target=my_thread_function)
my_thread.start()

# Wait for user input to stop the thread
result = easygui.ynbox("Do you want to stop the thread?", "Question")
if result:
    stop_thread = True
    my_thread.join()
    easygui.msgbox("Thread terminated.")
else:
    easygui.msgbox("Thread is still running.")

In this example, the my_thread_function() contains a loop that calls easygui.ynbox() to ask the user a question and block until the user responds. The loop continues until the stop_thread flag is set to True.

The main program prompts the user with an easygui.ynbox() to ask if they want to stop the thread. If the user answers yes, the stop_thread flag is set to True and the main program waits for the thread to terminate using my_thread.join(). If the user answers no, the main program continues to run and the thread continues to execute.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-05-09 11:00:00 +0000

Seen: 8 times

Last updated: Jul 05 '21