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:
JavaScript
x
35
35
1
from tkinter import *
2
3
flag=False
4
5
def test_loop():
6
while flag==True:
7
print("True")
8
while flag==False:
9
print("False")
10
11
def start():
12
global flag
13
flag=True
14
test_loop()
15
16
def stop():
17
global flag
18
flag=False
19
test_loop()
20
21
root = Tk()
22
root.title("Test")
23
root.geometry("500x500")
24
25
app = Frame(root)
26
app.grid()
27
28
start = Button(app, text="Start", command=start)
29
stop = Button(app, text="Stop", command=stop)
30
31
start.grid()
32
stop.grid()
33
34
root.mainloop()
35
Advertisement
Answer
Ok I managed to solve the problem, using a flag system indeed.
JavaScript
1
43
43
1
from tkinter import *
2
import threading
3
4
5
def st1():
6
global go1
7
global go2
8
go1=True
9
while go1==True:
10
go2=False
11
print('Start')
12
13
def st2():
14
global go1
15
global go2
16
go2=True
17
while go2==True:
18
go1=False
19
print('Stop')
20
21
22
def thread1():
23
threading.Thread(target=st1).start()
24
25
def thread2():
26
threading.Thread(target=st2).start()
27
28
29
root = Tk()
30
root.title("Test")
31
root.geometry("500x500")
32
33
app = Frame(root)
34
app.grid()
35
36
start = Button(app, text="Start", command=thread1)
37
stop = Button(app, text="Stop", command=thread2)
38
39
start.grid()
40
stop.grid()
41
42
root.mainloop()
43
Thanks for your help it was helpfull.