Unable to cancel infinite Tkinter (nested) after loop Unable to cancel infinite Tkinter (nested) after loop tkinter tkinter

Unable to cancel infinite Tkinter (nested) after loop


Whenever you call the function again, you need to update that ID so that — as you suspected — you have a reference you can pass to after_cancel. You already store that reference as self.run_id_1, but you don't update one.

The simplest way to do it would be to add a check if color == 'red' then set self.run_id_1 = self.after(...), and likewise for 'green' and self.run_id_2.

However, I should note that the structure of your moving_square function is not ideal. One reason you might have found it hard to locate what to change is that it's already overly parametrized. You should either divide its work up a little, splitting into various functions that are more specific. Or you could create a table of data to store the relevant states and ids of the scrolling rows so you can streamline the logic.