Reputation: 171
I have a function bound to the left mouse button that creates a piece on a playing board. In the end of that function, I call another function that creates another piece placed by the computer. I want this to be delayed, but so far I have not been able to do it.
I tried using "after" when I call the second function in the end of the first function, but that delays the initial function too, so both pieces are placed after the set time instead of one instantly, and then the other after a delay.
Edit: Tried this, but still the same issue. Is something wrong with this piece of code?
def onClick(self, event):
self.newMove(event)
self.gui.after(2000, self.AI())
So my question is basically how this could be solved in a neat way.
Upvotes: 0
Views: 3569
Reputation: 385840
Using after
is how you accomplish what you want.
The mistake in your code is that you're immediately calling the function in your after
statement. after
requires a reference to a function. Change your statement to this (note the lack of ()
after self.AI
)
self.gui.after(2000, self.AI)
Here is an example that automatically draws a second circle two seconds after you click:
import Tkinter as tk
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.canvas = tk.Canvas(self, width=400, height=400)
self.canvas.pack(fill="both", expand=True)
self.canvas.bind("<1>", self.on_click)
def on_click(self, event):
self.draw_piece(event.x, event.y)
self.after(2000, self.draw_piece, event.x+40, event.y+40, "green")
def draw_piece(self, x, y, color="white"):
self.canvas.create_oval(x-10, y-10, x+10, y+10, outline="black", fill=color)
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()
Upvotes: 3