Skip to content
Advertisement

Start and stop command to break a loop

I’m working on a webscraping code, and the process is quite long. Thus, I would like to start and stop it in a fancy way, with a button using tkinter. But I couldn’t find any solution on the web.

  • The .after() function doesn’t seems to be a good option as I don’t want to restart my loop each time. My loop is already working based on urls readed from another document and parsing for each.
  • I tried the thread option with .join(). But couldn’t manage to solve my problem with it. But maybe I don’t write my code correctly.

My problem can be formulate as follow:

Start → Read urls doc and launch parsing loop.

Stop → Stop parsing and save content.

For instance I would like something like the following code to work:

from tkinter import *

flag=False

def test_loop():
    while flag==True:
        print("True")
    while flag==False:
        print("False")

def start():
    global flag
    flag=True
    test_loop()

def stop():
    global flag
    flag=False
    test_loop()

root = Tk()
root.title("Test")
root.geometry("500x500")

app = Frame(root)
app.grid()

start = Button(app, text="Start", command=start)
stop = Button(app, text="Stop", command=stop)

start.grid()
stop.grid()

root.mainloop()

Advertisement

Answer

Ok I managed to solve the problem, using a flag system indeed.

from tkinter import *
import threading


def st1():
    global go1
    global go2
    go1=True
    while go1==True:
        go2=False
        print('Start')

def st2():
    global go1
    global go2
    go2=True
    while go2==True:
        go1=False
        print('Stop')


def thread1():
    threading.Thread(target=st1).start()

def thread2():
    threading.Thread(target=st2).start()


root = Tk()
root.title("Test")
root.geometry("500x500")

app = Frame(root)
app.grid()

start = Button(app, text="Start", command=thread1)
stop = Button(app, text="Stop", command=thread2)

start.grid()
stop.grid()

root.mainloop()

Thanks for your help it was helpfull.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement