简体   繁体   中英

Problems with update and update_idletasks

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()

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM