Search code examples
pythonloopsanimationtkinterdelay

while loop not working in tkinter animation


I am trying to create an animation of a turning wheel and want to have a small delay in a while loop and then update the wheel every time. I have tried both the "after" function in tkinter as well as the "sleep" function in python but it either crashes or finishes the conputation and only shows me the last position without the actual animation as the wheel is turning.

The function I created for the turning wheel:

def turning():
    #initial wheel position
    global position
    pos(position)

    #infinite loop turning the wheel
    while(1):
        root.after(1000, spin)

def spin():
    global position
    global speed
    delspike() #delete current wheel
    position += speed #calculate next position
    if position > 360:
        position -= 360
    pos(position) #draw new wheel

why is this not working?


Solution

  • after is used inside the function you are trying to put in a loop:

    def f():
        ...
        root.after(1000, f)
    

    (1000 means 1000 milliseconds which is 1 second. This means the program will perform an operation every 1 second. And you can change it to any number you wish.) Also, keep in mind that, using infinite while loop (while True, while 1 etc.) in Tkinter will make the window not responding. We have discussed this here a lot. You could find this if you had researched on SO.