VipinSC
VipinSC

Reputation: 11

Animate the color of rectangle

I want to change the color of rectangle after a certain period of time.

I tried root.after() method but it is not working.

    import time
    from tkinter import *

    def task():
      canvas= Canvas()
      canvas.create_rectangle(0,0,100,100,fill='red')
      canvas.pack()
      time.sleep(2)
      canvas.create_rectangle(0,0,100,100,fill='blue')
      canvas.pack()
      time.sleep(2)
      print("Testing...")


    root = Tk()
    canvas = Canvas(root)
    while(1):
      task()
      root.mainloop()

Given code running continuously and root windows get hang for certain time. Rectangle color should change after 2 seconds of delay.

Upvotes: 0

Views: 994

Answers (1)

Saad
Saad

Reputation: 3430

Using time.sleep() hangs the window as well as while loop. To use time.sleep in tkinter we use after(ms) (ms-milliseconds) in the functions so the GUI won't hang.

While does the same, so we use after(ms, callback, args) function.

Here is an example of what you are trying to achieve. The rectangle will change his color every 1000ms (1 sec) from red to blue - blue to red so on. Also in your code you were creating a new canvas and rectangle every 4 secs. What I did is, I defined one canvas and one rectangle outside the task() function and gave the rectangle a tag (tag='rect') for the reference through which edit that one rectangle's color without creating unnecessary items. I hope this helped you.

Example:

from tkinter import *

root = Tk()
canvas = Canvas(root)
canvas.pack()
canvas.create_rectangle(0,0,100,100,fill='red', tag='rect')

def task():
    l = root.after(1000, task)

    if int(l.split('#')[1]) % 2 == 0:
        canvas.itemconfig('rect', fill='blue')
    else: 
        canvas.itemconfig('rect', fill='red')

task()

root.mainloop()

Upvotes: 1

Related Questions