Andrea Andrea - 3 months ago 11
Python Question

Python Simon Game: I Cannot Make the Command of the Button Work the Way I Need

I am working on a Simon Game in Python using Tkinter and I am having problems making work the command of the button.

For the game the activebackground of the button must change from the normal color to another color when clicked and then return to the normal color and I must be able to repeat the action for an indefinite amount of clicks.

The necessary code for this is:

import Tkinter

base = Tkinter.Tk()

fr = Tkinter.Frame(base, bg="black", width="238", height="238")

def yellowClick():

yellow.configure(activebackground="yellow3")

yellow = Tkinter.Button(base, bd="0", highlightthickness="0",
width="7", height="5", activebackground="yellow",
bg="yellow3", command = yellowClick)

yellow.place(x = 30, y = 30)

fr.pack()

base.mainloop()


Here the actual code in the yellowClick() function makes the activebackground of the button to properly change color to yellow3, but I don't know how to return it after 3 seconds to yellow, and then be able to repeat the action for an indefinite amount of clicks.

I tried with time.sleep() in this way:

def yellowClick():

yellow.configure(activebackground="yellow3")

time.sleep(3)

yellow.configure(activebackground="yellow")


But it only makes the button to turn yellow and last 3 seconds. Instead of turning yellow3, wait 3 seconds and then return to yellow.

Any help is welcome.

Answer

but I don't know how to return it after 3 seconds to yellow,

Tkinter widgets have a method named after for precisely this sort of thing. If you want to change it to a different color in three seconds you can do this:

 yellow.configure(activebackground="yellow3")
 yellow.after(3000, lambda: yellow.configure(activebackground="yellow"))

This creates an anonymous function that will run approximately three seconds (3000 milliseconds) in the future.

Comments