How can I bind two delayed functions to a Button in Python?

63 Views Asked by At
from tkinter import *
    
def update():
    myEntry.config(bg="red")
def update2():
    myEntry.config(bg="blue")

root = Tk()
myEntry = Entry(root)
myEntry.pack()
myButton = Button(text="test", command=lambda: [myEntry.after(2000, update), myEntry.after(2000, update2)])
myButton.pack()
root.mainloop()

I tried to bind two delayed functions to a button, but only the second one works :(

1

There are 1 best solutions below

0
Bryan Oakley On

Create a function, and call your delayed functions from that function. I'm going to assume you actually want the second function to happen 2 seconds after the first, so I've adjusted the time in the call to after.

def run_test():
    myEntry.after(2000, update)
    myEntry.after(4000, update2)
...
myButton = Button(text="test", command=run_test)

While you can use lambda, it makes the code harder to read and harder to debug, so I always recommend having a special-purpose function for callbacks whenever possible.