0

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.

0

1 Answer 1

3

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()
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the reply! Your code works great, but when I try to implement a similar structure in my program it still delays both functions. Edited my post with what I have written, can you check if I did something wrong there?
You have extra parenthesis; you need to give the name of a function: self.gui.after(2000, self.AI)
Edit: Fixed the problem. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.