Python 用我启动的按钮打破一个循环?

Python 用我启动的按钮打破一个循环?,python,python-3.x,tkinter,raspberry-pi,picamera,Python,Python 3.x,Tkinter,Raspberry Pi,Picamera,我想用我启动的那个按钮来打破一个循环。 下面的代码不起作用,因为它在sleep2之后结束循环 我知道camera.capture\u continuous是专为PiCamera设计的,但也许有人能帮我找到解决方案 我没有使用过picamera,所以这行被注释掉了,但是尝试下面的方法,您将不得不使用线程,否则您的主UI线程将被锁定。 我添加了另一个按钮和一个标签,只是为了帮助显示进程正在一个单独的线程上运行 import tkinter as tk from time import sleep i

我想用我启动的那个按钮来打破一个循环。 下面的代码不起作用,因为它在sleep2之后结束循环

我知道camera.capture\u continuous是专为PiCamera设计的,但也许有人能帮我找到解决方案


我没有使用过picamera,所以这行被注释掉了,但是尝试下面的方法,您将不得不使用线程,否则您的主UI线程将被锁定。 我添加了另一个按钮和一个标签,只是为了帮助显示进程正在一个单独的线程上运行

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()

如果您需要线程能够启动、停止、启动、停止,请看一看。

用按钮中断循环是什么意思?我想在照相机中中断文件名。。。。循环编辑:我不确定它是否叫做循环,它是一个循环。我明白,我对。。。带有按钮部分。我通过按rec_btn来启动循环,过了一段时间,我不想再按同一个rec_btn来中断循环。@zr0gravity7感谢您的努力!:但我不懂JavaScript,我已经用tkinter编写了程序的其余部分。谢谢!:这完美地解决了我的问题,即当循环处于活动状态时GUI会冻结。用同一个按钮停止timelapse不起作用,但我在if rec_btn附近添加了camera.close。。。这会帮我完成任务的。
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()