0

I've been learning python for a month now and run into my first brick wall. I have a large art viewer GUI program and at one point want to put an image on screen with a countdown counter-approx every 5 secs. I thought of a code such as the one below The problem is that this uses update and all my reading says that update is bad (starts a new event loop (?)) and that I should use update_idletasks. when I replace update with update_idletasks in the code below the countdown button is not visible until it reaches single figures, update superficially works fine. But also the q bound key calls the subroutine but has no effect

from tkinter import *
import sys
import time

root = Tk()

def q_key(event):
    sys.exit()

frame=Frame(root, padx=100, pady=100, bd=10, relief=FLAT)
frame.pack()
button=Button(frame,relief="flat",bg="grey",fg="white",font="-size 18",text="60")
button.pack()
root.bind("q",q_key)

for x in range(30, -1, -5) :
   button.configure(text=str(x))
   button.update()
   print(x)
   button.after(5000)

root.mainloop()
wjandrea
  • 28,235
  • 9
  • 60
  • 81
tony
  • 19
  • 3
  • Actually,it wil also block your code,you could think about make a function and call `.after()` to do it. – jizhihaoSAMA Apr 30 '20 at 16:48
  • Does this answer your question? [tkinter: how to use after method](https://stackoverflow.com/questions/25753632/tkinter-how-to-use-after-method) – stovfl Apr 30 '20 at 17:25
  • First you have to understand [Event-driven_programming](https://en.m.wikipedia.org/wiki/Event-driven_programming). Read through [`[tkinter] event driven programming`](https://stackoverflow.com/search?q=is%3Aanswer+%5Btkinter%5D+event+driven+programming+entry) – stovfl Apr 30 '20 at 17:28

1 Answers1

1

In this case you don't need update nor update_idletasks. You also don't need the loop, because tkinter is already running in a loop: mainloop.

Instead, move the body of the loop to a function, and call the function via after. What happens is that you do whatever work you want to do, and then schedule your function to run again after a delay. Since your function exits, tkinter returns to the event loop and is able to process events as normal. When the delay is up, tkinter calls your function and the whole process starts over again.

It looks something like this:

def show(x):
    button.configure(text=x)
    if x > 0:
        button.after(5000, show, x-5)

show(30)
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685