Reputation: 1
I am coding in python2.7 using Tkinter. I need a set of rectangles to change color one after another. But when I write the item.config one after one in my function, they execute together at the end of the execution.
def button(self):
print "hi"
self.canvas.itemconfig(self.figure1, fill="green")
time.sleep(3)
print "hello"
self.canvas.itemconfig(self.figure2, fill="green")
time.sleep(3)
print "okay"
time.sleep(3)
self.canvas.itemconfig(self.figure3, fill="green")
When I run this, all the print statements complete and then the three figures change color together. I need it to change one after the other as each statement gets executed/printed.
I am new to Python and Tkinter. Any suggestions and ideas why this is happening? Thanks!
Upvotes: 0
Views: 1521
Reputation: 33223
Here is a simple example that demonstrates how to perform a chain of actions using after
to delay events while keeping the Tk event loop running. I only have Python 3 so you may need to modify slightly to work with Python 2.7.
#!/usr/bin/python
from tkinter import *
def toggle(canvas, items):
if len(items) > 0:
canvas.itemconfigure(items[0], fill="green")
canvas.after(1000, lambda: toggle(canvas, items[1:]))
return
root = Tk()
canvas = Canvas(root, background="white")
canvas.pack(fill='both', expand=True)
figure1 = canvas.create_rectangle(10,10,80,80, fill="red")
figure2 = canvas.create_rectangle(100,10,180,80, fill="red")
figure3 = canvas.create_rectangle(200,10,280,80, fill="red")
canvas.after(1000, lambda: toggle(canvas, [figure1, figure2, figure3]))
root.mainloop()
Keeping the event loop operating is crucial. You cannot use sleep
in GUI applications unless you create a worker thread. Typically you don't need to anyway. The after
call puts a task onto the UI event queue for you to be run at a later time and if you capture the after token you can even cancel them (for instance if you require a timeout function for something.).
Upvotes: 2