- Trending Categories
- Data Structure
- Operating System
- MS Excel
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to run an infinite loop in Tkinter?
To run an infinite loop in Tkinter, we will use the after method to call a method recursively after a specified time period until the user decides to stop the loop. Let's take a simple example and see how to start and stop an infinite loop.
Import the required libraries and create an instance of tkinter frame.
Set the size of the frame using win.geometry method.
Next, create a user-defined function "infinite_loop" which will call itself recursively and print a statement on the window.
Define two more user-defined functions, start() and stop(), to control the infinite_loop. Define a global variable "condition". Inside start(), set condition=True and inside stop(), set condition=False.
Create two buttons to call the start() and stop() functions.
Use the after() method to call the infinite_loop recursively after every 1 second.
Finally, run the mainloop of the application window.
# 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 condition=True def infinite_loop(): if condition: Label(win, text="Infinite Loop!", font="Arial, 25").pack() # Call the infinite_loop() again after 1 sec win.after(1000, infinite_loop) def start(): global condition condition=True def stop(): global condition condition=False # Create a button to start the infinite loop start = Button(win, text= "Start the Loop", font="Arial, 12", command=start).pack() stop = Button(win, text="Stop the Loop", font="Arial, 12", command=stop).pack() # Call the infinite_loop function after 1 sec. win.after(1000, infinite_loop) win.mainloop()
When you run this code, it will produce the following output −
Click the button "Start the Loop" to run the infinite loop which will keep printing "Infinite Loop!" after every second. Click "Stop the Loop" to stop the infinite loop.
- Related Articles
- How do you create a Tkinter GUI stop button to break an infinite loop?
- How to create an infinite loop in C#?
- How to stop an infinite loop safely in Python?
- How we can come out of an infinite loop in Python?
- How to run matplotlib in Tkinter?
- Infinite while loop in Java
- The Infinite Loop in Perl
- How do you run your own code alongside Tkinter's event loop?
- Java infinite for loop
- Incremental Java infinite loop
- What keyboard command we have to stop an infinite loop in Python?
- Java infinite do-while loop
- How can we run Matplotlib in Tkinter?
- How to create Tkinter buttons in a Python for loop?
- How to stop a loop with a stop button in Tkinter?