1

I am trying to get a rectangle to move continuously like a while loop however whenever I run the program it says I've reached the max recursion depth instantly, any way to fix this?

code:

from tkinter import *

def move(rect):
    canvas.move(rect, 10, 0)
    root.after(10, move(rect))
root = Tk()
root.overrideredirect(1)
root.geometry("400x400")
canvas = Canvas(root, width=400, height=400)
rect = canvas.create_rectangle(0, 0, 50, 50, fill = "red")
canvas.pack()
root.after(10, move(rect))
root.mainloop()
jamesdoh32
  • 21
  • 1
  • 5
    Does this answer your question? [tkinter: how to use after method](https://stackoverflow.com/a/25753719/7414759) – stovfl May 24 '20 at 15:06

1 Answers1

0

As @stovfl said, you shouldn't use the .after() method inside the function.

Instead, this would be your code:

from tkinter import *
root = Tk()
root.geometry("400x400")
canvas = Canvas(root, width=400, height=400)
canvas.pack()
def move(rectangle):
    canvas.move(rect, 10, 0)
    root.after(10, lambda: move(rect))

rect = canvas.create_rectangle(0, 0, 50, 50, fill = "red")
root.after(10, lambda: move(rect))
root.mainloop()

Or, if you want to do it differently for some reason,

from tkinter import *
root = Tk()
root.geometry("400x400")
canvas = Canvas(root, width=400, height=400)
canvas.pack()
def move(rectangle):
    canvas.move(rect, 10, 0)
    root.after(10, lambda: move(rect))

rect = canvas.create_rectangle(0, 0, 50, 50, fill = "red")
move(rect)
root.mainloop()

Both of them work perfectly, though the former is more consistent(at least in my opinion).

Hope this helps!

10 Rep
  • 2,217
  • 7
  • 19
  • 33