How to use Tkinter after method to give the impression of a wheel spinning?

I'm trying to create three separate 'wheels' that change the starting position of the first arc in order to give the impression of the wheel spinning. Tkinter will draw the first wheel on the canvas and delete it after 1 second, but the subsequent wheels are never drawn.

    from tkinter import Canvas, Tk

    tk = Tk()
    tk.geometry('500x500')

    canvas = Canvas(tk)
    canvas.pack(expand=True, fill='both')

    in_list = [1,1,1,1,1,1,1]

    arc_length = 360 / len(in_list)
    first_mvmt = arc_length / 3
    second_mvmt = arc_length * 2 / 3

    mvmt_list = [0, first_mvmt, second_mvmt]

    for mvmt in mvmt_list:
        for i in range(len(in_list)):
            start = i * arc_length
            extent = (i + 1) * arc_length
            arc = canvas.create_arc(5, 5, 495, 495, outline='white', start=start + mvmt, extent=extent)

        canvas.after(1000)
        canvas.delete('all')


    tk.mainloop()

Also please excuse my poor formatting, this is my first post on stackoverflow

1 answer

  • answered 2022-05-07 12:21 Helder Sepulveda

    Your outer loop has only 3 items in it, that is not going give the impression of a wheel spinning...
    Take a look a the code below:

    • I changed your loop to 100
    • Added a tk.update() after inner loop
    • Added a sleep(0.05) instead of your after(1000)
    import time
    from tkinter import Canvas, Tk
    
    tk = Tk()
    tk.geometry('500x500')
    
    canvas = Canvas(tk)
    canvas.pack(expand=True, fill='both')
    
    in_list = [1,1,1,1,1,1,1]
    arc_length = 360 / len(in_list)
    
    for mvmt in range(100):
        canvas.delete('all')
        for i in range(len(in_list)):
            start = i * arc_length
            extent = (i + 1) * arc_length
            arc = canvas.create_arc(5, 5, 495, 495, outline='white', start=start + mvmt, extent=extent)
        tk.update()
        time.sleep(0.05)
    
    tk.mainloop()
    

    it should look like this:

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum