How do you create a Tkinter GUI stop button to break an infinite loop?

TkinterPythonGUI-Programming

Tkinter is a Python library which is used to create GUI-based application. Let us suppose that we have to create a functional application in which a particular function is defined in a loop. The recursive function will display some text in a Label widget for infinite times.

To stop this recursive function, we can define a function which changes the condition whenever a button is clicked. The condition can be changed by declaring a global variable which can be either True or False.

Example

# Import the required library
from tkinter import *

# Create an instance of tkinter frame
win= Tk()

# Set the size of the Tkinter window
win.geometry("700x350")

# Define a function to print something inside infinite loop
run= True

def print_hello():
   if run:
      Label(win, text="Hello World", font= ('Helvetica 10 bold')).pack()
   # After 1 sec call the print_hello() again
   win.after(1000, print_hello)
def start():
   global run
   run= True

def stop():
   global run
   run= False

# Create buttons to trigger the starting and ending of the loop
start= Button(win, text= "Start", command= start)
start.pack(padx= 10)
stop= Button(win, text= "Stop", command= stop)
stop.pack(padx= 15)

# Call the print_hello() function after 1 sec.
win.after(1000, print_hello)
win.mainloop()

Output

Now, whenever we click the "Stop" button, it will stop calling the function.

raja
Published on 07-Jun-2021 11:03:33
Advertisements