0

I have a 'Start' button which starts a function, but also want a button that can end that specific function is there a way I can do this here's my code:

from tkinter import *
from tkinter.ttk import *

root = Tk()
root.geometry('900x900')
def start():
    for count in range(100):
        Label(root,text='hi').pack()

def stop():
    #What code should I use to stop 'def start'
    print('')

Button(root,text='stop',command=lambda: stop).pack()
Button(root,text='start',command=lambda: start()).pack()

root.mainloop()

Thanks in advance

coderoftheday
  • 1,987
  • 4
  • 7
  • 21
  • Does this answer your question? [How to stop a loop triggered by tkinter in Python](https://stackoverflow.com/questions/36847769/how-to-stop-a-loop-triggered-by-tkinter-in-python) – Olvin Roght May 27 '20 at 18:59
  • [This](https://stackoverflow.com/questions/39555463/tkinter-how-to-stop-a-loop-with-a-stop-button) also could help. – Olvin Roght May 27 '20 at 19:00
  • And [this](https://stackoverflow.com/questions/27050492/how-do-you-create-a-tkinter-gui-stop-button-to-break-an-infinite-loop) – Olvin Roght May 27 '20 at 19:00

1 Answers1

0

You can try use the library threading and run two thread at the same time.

Here I leave the code.

from tkinter import *
from tkinter.ttk import *
from time import sleep
import threading
from threading import Thread
root = Tk()
root.geometry('900x900')

def start():
    global flag
    for count in range(100):
        if flag:break
        print(flag)
        Label(root,text='hi').pack()
        sleep(1)

def stop():
    global flag
    flag=True
    print(flag)
if __name__=='__main__':
    flag=False
    thread=[]
    Button(root,text='stop',command=lambda: Thread(target=stop).start()).pack()
    Button(root,text='start',command=lambda: Thread(target=start).start()).pack()
    root.mainloop()
Sho_Lee
  • 149
  • 4