Search code examples
pythonbuttontkinterjquery-animatemotion

Button motion animation in tkinter


I want to move a button animated. For example it starts from x=0 and y=0, after 0.1 second x=1 and y=1 ... x=50 and y=50.

I tried this:

import tkinter
import time

b=tkinter.Button(text="Example")
for i in range(50): 
    i+=1
    b.place(x=i, y=i)
    time.sleep(0.1)

The window opened after all place commands were executed.


Solution

  • Do not pause/sleep your python program. As pointed out by @Mike-SMT, it may end up freezing up your mainloop. If you want to do animation, after is the way to go.

    import tkinter as tk
    
    root = tk.Tk()
    b = tk.Button(root, text="Example")
    
    def move(i):
        if i<=50:
            b.place(x=i, y=i)
            b.after(100, lambda: move(i)) #after every 100ms
            i = i+1
    
    move(0) #Start animation instantly
    root.mainloop()
    

    enter image description here