Search code examples
pythonuser-interfaceconcurrencywhile-loopraspberry-pi

Python - How do I continuously repeat a sequence without a While loop and still be able to stop the sequence at any time


I have a Raspberry Pi with the Piface adaptor board. I have made a GUI which controls the LED's on the Piface board. I wrote a small piece of code to make the LED's run up and down continuously, like Knight Riders car, using a While loop. I then wrote another piece of code that created a GUI. In the GUI is a button that starts the LED's running up and down continuously with the While loop piece of code. What I want to do is to have that GUI button start the LED running sequence, and then the same button stop the sequence at any time.

I do understand that the code is sitting/stuck in the While loop. And hence any buttons in the GUI are not going to have an effect.

So is there a better way of doing it? Any pointers would be appreciated.

Thanks in advance.


Solution

  • Another option is to run the LED while loop in a separate thread. Like in the next code. The while loop is stopped by toggling the shared led_switch variable.

    """
    blinking LED
    """
    
    import tkinter as tk
    import threading
    import time
    
    led_switch=False
    
    def start_stop():
        global led_switch
        led_switch=not led_switch
        if led_switch:
            t=threading.Thread(target=LED)
            t.start()
    
    def LED():
        while led_switch:
            print('LED on')
            time.sleep(1)
            print('LED off')
            time.sleep(1)
    
    root=tk.Tk()
    
    button=tk.Button(root,command=lambda: start_stop(),text='start/stop')
    button.pack()
    tk.mainloop()