Reputation:
I am trying to make a circle in tkinter change colors after the window has been initiated. I've looked at this question, and I know how to change the colors after stating the variable. I'm trying to make a traffic light (much like the person in the question I looked at), but I can't update the color change after the screen comes up. This is what I have so far
root = tk.Tk()
canvas = tk.Canvas(root)
light_1 = canvas.create_oval(*coordinates here*, fill='green')
root.mainloop()
and to change the color use canvas.itemconfig(light_1, fill='blue')
and I can't just do a time.sleep(1)
because then the root.mainloop()
is only reached after i change the color. There is no visual feedback of it changing
Upvotes: 1
Views: 5317
Reputation: 13729
You can't use time.sleep()
anywhere in tkinter code because it blocks the tkinter mainloop from running. The solution is to add your code to the tkinter mainloop using the after
method:
def change_color():
canvas.itemconfig(light_1, fill='blue')
root = tk.Tk()
canvas = tk.Canvas(root)
light_1 = canvas.create_oval(*coordinates here*, fill='green')
root.after(1000, change_color) # 'after' uses milliseconds, so 1,000 = 1 second
root.mainloop()
Upvotes: 4