Home > Software design >  Executing a command before window.destroy() in tkinter
Executing a command before window.destroy() in tkinter

Time:12-16

I am learning to build basic GUIs with Tkinter in order to use it in a project.

I would like to have a button that runs a certain task, then prints "Task done", then waits 1 second, and then closes the window.

Here's what I tried to do :

from tkinter import *
from time import *

def PrintAndClose():
    label.configure(text="Task done")
    t1 = time()
    t2 = time()
    while t2-t1 < 1:
        t2 = time()
    window.destroy()

window = Tk()
window.title("Task doer")
window.geometry('400x400')

label = Label(window, text="Task to be done")
label.pack()


bouton = Button(window , text = "Do the task", command=PrintAndClose)
bouton.pack()

window.mainloop()

When I run the GUI and click the button, it waits 1 second and then closes the window, but it does not change the label.

Is there anything wrong in what I'm doing ? I guess it's more complicated than that.

Thanks for your help !

CodePudding user response:

It turns out using the after method as Matiss suggested fixed it.

  • Related