mani varma
mani varma

Reputation: 31

How to stop execution of a function on button click in Python 3?

I'm making a small GUI aplication with tkinter buttons, when button1 is clicked, a function which has infinite loop runs.

I would like to have the possibility to stop the process with another button and reset the aplication to the initial state. I don't know how to do because when the button1 starts the script , button2 is blocked. I want to stop execution of function1 on button2 click. This is my code .

from tkinter import * 
root = Tk() 

def function1():
 x =0 
 while True :  # infinite loop
   print(x)
   x = x + 1  

def function2():
 sys.exit()

btn1 = Button(root, text ="Button 1", command = function1) 
btn1.place(x=200, y=200) 

btn2 = Button(root, text ="Button 2", command = function2) 
btn2.place(x= 300,y=300) 

root.geometry("400x400")
mainloop()

Thank you.

Upvotes: 1

Views: 6633

Answers (1)

theashwanisingla
theashwanisingla

Reputation: 477

you can not run the infinite loop in buttons instead you can use recursion. You can call a function recursively and fuction1, function2 can be the functions used to control any variable. Please go thru the following code:

from tkinter import *

running = False
x=0

def scanning():
    global x
    if running: 
        x = x+1
        print (x)
    # After 10 milli second, call scanning again (create a recursive loop)
    root.after(10, scanning)

def start():
    global running
    running = True

def stop():
    global running
    running = False

root = Tk()
root.title("Continuous Loop")
root.geometry("100x100")

app = Frame(root)
app.grid()

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

start.grid()
stop.grid()

root.after(1000, scanning)  # After 1 second, call scanning
root.mainloop()

Hope this will help.

Upvotes: 3

Related Questions