How do you run your own code alongside Tkinter's event loop?

PythonTkinterGUI-Programming

Tkinter is widely used to create and develop GUI based applications and games. Tkinter provides its window or frame where we execute our programs and functions along with other attributes.

Let us consider that we are working with a particular application and we want to write the changes in the code while running the application. Tkinter provides a callback method which can be used to run the window while iterating over it. We can keep running the window using the after(duration,task) method that will basically run the changes after a duration.

In this example, we will create a window which prints the numbers in the range (0 to 9) whilst running the main window or frame.

Example

#Import the required libraries
from tkinter import *
from tkinter import messagebox
#Create an instance of tkinter frame or window
win= Tk()

#Set the geometry
win.geometry("700x200")

#Define the function for button
def some_task():
   for i in range(10):
      print(i)

      #Recursively call the function
      win.after(2000, some_task)

#Keep Running the window
win.after(2000, some_task)
win.mainloop()

Output

Running the above code will keep printing the numbers in the range (0 to 9) on the console, and along with that, it will display the main window.

0
1
2
3
4
5
6
7
8
9
…….

raja
Published on 04-Mar-2021 13:51:47
Advertisements