Search code examples
pythonpython-3.xtkinterraspberry-pipicamera

Breaking a loop with the button I started it?


I want to break a loop with the same button I started it. The code below doesn't work because it ends the loop after "sleep(2)".

I know that "camera.capture_continuous" is specific for the PiCamera but maybe someone can still help me to find a solution. ;)

import tkinter as tk
from picamera import PiCamera
root = tk.Tk()
camera = PiCamera()




def start_tl():
    if rec_btn.config('text')[-1] == 'START':
        rec_btn.config(text='STOP')
        for filename in camera.capture_continuous('/tl_img{counter:03d}.jpg', use_video_port=True):
            sleep(2)
            if rec_btn.config('text')[-1] == 'START':
                break

    
             
rec_btn = tk.Button(root,text="START", command=start_tl)
rec_btn.pack()



root.mainloop()

Solution

  • I have not worked with the picamera, so that line is commented out, but try the following, you will have to use threading otherwise your main UI thread will be locked up. I added another button and a label just to help show that the process is running on a separate thread.

    import tkinter as tk
    from time import sleep
    import threading
    
    root = tk.Tk()
    
    def start_tl():
        if rec_btn['text'] == 'STOP':
            t.join(1)
            rec_btn.config(text='START')
            return
    
        if rec_btn['text'] == 'START':
            t.start()
            rec_btn.config(text='STOP')
            return
    def exit_tl():
        root.destroy()
    
    def process_file():
        i = 1
        while rec_btn['text'] == 'STOP':
            i = i+1
            rec_btn.update()
            sleep(5)
            rec_lbl["text"] = "{}".format(i)
            # for filename in camera.capture_continuous('/tl_img{counter:03d}.jpg', use_video_port=True):
                #do something with the file??
    
    
    rec_btn = tk.Button(root, text="START", command=lambda: start_tl())
    rec_btn_exit = tk.Button(root, text="Exit", command=lambda: exit_tl())
    rec_lbl = tk.Label(root,text="")
    rec_btn.pack()
    rec_btn_exit.pack()
    rec_lbl.pack()
    
    t = threading.Thread(target=process_file)
    
    root.mainloop()
    

    if you need your thread to be able to start, stop, start, stop have a look at this question and answers.