Skip to content Skip to sidebar Skip to footer

Python Tkinter Coords Function Not Moving Canvas Objects Inside Loop

I have a function that reads locations from a text file, parses them, then moves the respective objects to the locations listed on a tkinter canvas using the coords function. The

Solution 1:

A very good rule of thumb in GUI development is to never call sleep. This freezes the GUI, and even if it's just for a few milliseconds it's still a bad practice.

The proper way to do animation in Tkinter is to write a function that displays a single frame, then reschedules itself using after. This allows the event loop to constantly service events while doing the animation.

For example, take the entire body of the for statement -- minus the sleep -- and put it into a method. Let's call this "refresh". Have this function re-schedule itself using after, like this:

def refresh():
    line = get_next_line()
    line = line.split('|')
    B_loc = line[0].split(':')[1].split(',')
    ...

    # call this function again in 20ms
    root.after(20, refresh)

Now all you need to do is implement get_next_line as a function and you're set. This will automatically allow the GUI to redraw itself each time yo update the coordinates.

Of course, you'll need to put in checks for when input is exhausted, and you might want to have a flag the user can set via a button that requests that the animation stops, etc.

Post a Comment for "Python Tkinter Coords Function Not Moving Canvas Objects Inside Loop"