0

I am trying to make a button that when clicked:

  1. Changes my label's text to "wrong answer"
  2. Has 2 seconds delay then changes it to "Shut down in 3..."
  3. Has 1 second delay then changes it to "Shut down in 2..."
  4. Has another 1 second delay then changes it to "Shut down in 1..."

Anyone know if this is possible?

def clickcancel():
    label.config(text = "Wrong answer!")
    sleep(2)
    label.config(text = "Shut down in 3...")
    sleep(1)
    label.config(text = "Shut down in 3...2...")
    sleep(1)
    label.config(text="Shut down in 3...2...1...")
001
  • 13,291
  • 5
  • 35
  • 66
Brxby
  • 23
  • 2
  • You should avoid `sleep` in a tkinter app. Use `after` instead. [Making a countdown timer with Python and Tkinter?](https://stackoverflow.com/a/10599462) – 001 Aug 27 '21 at 12:50
  • isnt there a way to use only one function? – Brxby Aug 27 '21 at 13:27

1 Answers1

2

When you call sleep your program does exactly that: it goes to sleep. That means that tkinter can't refresh the window to show the new text. As a general rule of thumb you should never call sleep in the same thread that the GUI is running in.

Instead of sleeping, tkinter has a method to schedule code to run in the future. This method is called after. It accepts a number of milliseconds for the delay, a function to call, and optional arguments to the command.

For example, here's one way to write your function:

def clickcancel():
    def setlabel(text):
        label.config(text=text)

    setlabel("Wrong answer!")
    label.after(1000, setlabel, "Shut down in 3...")
    label.after(2000, setlabel, "Shutdown in 3...2...")
    label.after(3000, setlabel, "Shutdown in 3...3...1...")
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685