def click():
button1.configure(bg="gray")
time.sleep(1)
button1.configure(bg="green")
button1 = Button(win, text="Button",bg="green",activebackground="red")
button1.pack()
I tryied to change button to gray for only second than change back to green. But it won't change to gray
CodePudding user response:
You need to bind that event after the packing
from tkinter import *
import time
def click(event):
if button1["background"] == "green":
time.sleep(3)
button1["background"] = "yellow"
else:
button1["background"] = "green"
root = Tk()
myContainer1 = Frame(root)
myContainer1.pack()
button1 = Button(myContainer1, text="Button", bg="green")
button1.pack()
button1.bind("<Button-1>", click) # binding event here
root.mainloop()
btw, solid resource on the subject, a bit dated but as an educational material - written perfectly - short :D http://thinkingtkinter.sourceforge.net/
CodePudding user response:
You have to do it this way. If you use the Time library, the software won't work or you can use the Threading module for multithreading in Python but This method is a bit complicated
from tkinter import *
def click(event):
def loop(i):
if i==1:
button1.configure(bg="gray")
elif i==2:
button1.configure(bg="red")
return
i=i 1
button1.after (1000, lambda : loop (i))
loop (1)
root = Tk()
myContainer1 = Frame(root)
myContainer1.pack()
button1 = Button(myContainer1, text="Button", bg="red")
button1.pack()
button1.bind("<Button-1>", click) # binding event here
root.mainloop()
CodePudding user response:
First click()
has never been executed. Second all updates are handled by tkinter mainloop()
, so those changes will be handled after the function click()
exits and the last change will be seen only.
You can use .after()
instead of sleep()
to change the color of the button back to green after one second:
def click():
button1.configure(bg="gray")
button1.after(1000, lambda: button1.configure(bg="green"))
button1 = Button(win, text="Button", bg="green", activebackground="red", command=click)
button1.pack()