I wrote this silly program in python using tkinter where I show a stickman being hit on the head with a hammer by using a button event to change the label's image to the picture showing the stickman being hit for a small time period. The picture Bonk2 is the one that shows this and Bonk1 is just the normal picture if the button hasn't been pressed (both of them I declared as PhotoImages).
The function doing that is given below and I use this function as the command argument for the button BONK -
import time
import tkinter as tk
count = 0
def bonk():
global count
print("bonked")
count += 1
counter.config(text = "Bonk counter: " + str(count))
if count < 5:
BONK.config(state = "disabled")
picture.config(image = Bonk2)
time.sleep(2) #delay
picture.config(image = Bonk1) #Changing back the image
BONK.config(state = "active")
else:
picture.config(image = Bonk4)
BONK.config(state = "disabled")
Now, tkinter won't update the GUI immediately because it actually batches the update to the GUI and executes it after the function call. This means the picture effectively doesn't change from Bonk1 to Bonk2 after the function execution (also the GUI hangs). Is there a workaround where the image changes from Bonk1 to Bonk2 immediately and I can change it back after a delay?
time.sleepbut root.after(2000, other_function)to executeother_functionafter 2000ms (2s) and inother_functionchange image - and tkinter will return from current function and it will update all GUI. OR useroot.update()beforesleepto force tkinter to update all GUIs.