Search code examples
pythonpopupalert

How to pop up an alert in Python and at the same time keep the process running?


I have a sample script below. The alert message will pop up but the user will have to acknowledge before the script could continue to run. So how do I pop up an alert in Python and at the same time keep the process running?

import random
import time
x = 0
while x <= 20:
    a = random.randint(1, 100)
    print (a)
    if a <= 10:
        ctypes.windll.user32.MessageBoxW(0, "The number generated is less than 10", "ALERT", 1)
    x += 1
    time.sleep(.5)

Solution

  • Use threading.Thread.

    This launches the alert in a separate thread, so that it does not block the main thread.

    import random
    import time
    import threading
    
    def alert():
        ctypes.windll.user32.MessageBoxW(0, "The number generated is less than 10", "ALERT", 1)
    
    for _ in range(20):
        a = random.randint(1, 100)
        print (a)
        if a <= 10:
            thread = threading.Thread(target=alert)
            thread.start()
        time.sleep(.5)