Fix Python – How do you run your own code alongside Tkinter’s event loop?


Asked By – Allan S

My little brother is just getting into programming, and for his Science Fair project, he’s doing a simulation of a flock of birds in the sky. He’s gotten most of his code written, and it works nicely, but the birds need to move every moment.

Tkinter, however, hogs the time for its own event loop, and so his code won’t run. Doing root.mainloop() runs, runs, and keeps running, and the only thing it runs is the event handlers.

Is there a way to have his code run alongside the mainloop (without multithreading, it’s confusing and this should be kept simple), and if so, what is it?

Right now, he came up with an ugly hack, tying his move() function to <b1-motion>, so that as long as he holds the button down and wiggles the mouse, it works. But there’s got to be a better way.

Now we will see solution for issue: How do you run your own code alongside Tkinter’s event loop?


Use the after method on the Tk object:

from tkinter import *

root = Tk()

def task():
    root.after(2000, task)  # reschedule event in 2 seconds

root.after(2000, task)

Here’s the declaration and documentation for the after method:

def after(self, ms, func=None, *args):
    """Call function once after given time.

    MS specifies the time in milliseconds. FUNC gives the
    function which shall be called. Additional parameters
    are given as parameters to the function call.  Return
    identifier to cancel scheduling with after_cancel."""

This question is answered By – Dave Ray

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0