Search code examples
pythonpython-3.xtkinterbuttonsleep

Tkinter - How do I make a button execute it's command function first and then later use the after function rather than waiting first?


I wanted to have the button first execute some code, then become inactive for some time to not cause issues, but rather than executing the code then sleeping, it only executes the code after it's done sleeping, no matter in what order I put the code in, here it is:

def sleepsometime():
    askbutton.config(state=tk.DISABLED)
    cd = 5000
    cmd = askbutton.config(state=tk.NORMAL)
    window.after(cd, cmd)

def startstartingstartthread():
    t = threading.Thread(target=start)
    t.setDaemon = True
    t.start()
    sleepsometime()
    

window = tk.Tk()
window.geometry("500x500")
window.config(background="black")
window.title("NFAI Assistant")
askbutton = tk.Button(window, text="Ask", width=10, height=5, command=startstartingstartthread, foreground="black", background="cyan")
askbutton.place(x=210, y=300)
nflabel = tk.Label(window, text="Ask NFAI assistant", font=("heluvica", 30), foreground="white", background="black")
nflabel.place(x=82, y=160)
global infolabel
infolabel = nflabel = tk.Label(window, text="", font=("heluvica", 30), foreground="white", background="black")
infolabel.place(x=0, y=440)

if __name__ == '__main__':
    window.mainloop()

I tried re-arranging the code and some other small things, but none of these work.


Solution

  • Your line: cmd = askbutton.config(state=tk.NORMAL) actually executes that function immediately. You want something that you can pass to windows.after() which will be executed after the timeout.

    Something like this:

    def sleepsometime():
        askbutton.config(state=tk.DISABLED)
        cd = 5000
        window.after(cd, lambda:askbutton.config(state=tk.NORMAL))