0

I want to move a rectangle from left to right with a step of 50,but the canvas doesn't draw the rectangle until it arrive right side.

import tkinter as tk
import time
root=tk.Tk()
c_width,c_height=500,250
cv = tk.Canvas(root,bg = 'white',width=c_width,height=c_height)

l_x=0
l_y=0
r_x=50
r_y=50
step=50
r1=cv.create_rectangle(l_x,l_y,r_x,r_y,fill='red')

while l_x<c_width-50:
   
   cv.delete(r1)
   l_x=l_x+step
   r_x=r_x+step   
   r1=cv.create_rectangle(l_x,l_y,r_x,r_y,fill='red')
   print(c_width,l_x)
   time.sleep(1)

cv.pack()
root.mainloop()

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • Instead of `time.sleep(1)` use `after()`. [tkinter: how to use after method](https://stackoverflow.com/a/25753719) – 001 May 05 '22 at 15:05

1 Answers1

0

It is not recommended to use while/for loop in tkinter application because it will block the tkinter mainloop() from handling pending events and updates. Use .after() instead.

Also you don't need to delete and recreate the rectangle item, just move the rectangle item using cv.move().

Below is the update code:

import tkinter as tk

root = tk.Tk()

c_width, c_height = 500, 250
cv = tk.Canvas(root, bg='white', width=c_width, height=c_height)
cv.pack()

l_x = 0
l_y = 0
r_x = 50
r_y = 50
step = 50
r1 = cv.create_rectangle(l_x, l_y, r_x, r_y, fill='red')

def move_rect(x):
    # move the rectangle by "step" pixels horizontally
    cv.move(r1, step, 0)
    x += step
    if x < c_width:
        cv.after(1000, move_rect, x)

cv.after(1000, move_rect, r_x)
root.mainloop()
acw1668
  • 40,144
  • 5
  • 22
  • 34