0

I have a program that shows an image. Every time the user presses enter, I recalculate the image, what takes some time:

root = tk.Tk()
def callback_enter(e):
    # Heavy computation

root.bind("<Return>", callback_enter)
root.mainloop()

The problem is, when the user presses enter multiple times, callback function will be called again and again, even when the user stopped pressing the button, since the program remembers all the key presses before. Is there a way callback_enter() removes all key presses, that have been done during its execution?

Natjo
  • 2,005
  • 29
  • 75

1 Answers1

1

the problem here is that your program, while is busy with image computation, cannot interact with the main loop that is buffering input. One way to approach it is to filter events with a time frame criterium; here is an implementation as example:

import time
import random
import Tkinter as tk

root = tk.Tk()

LAST_CALL_TIME = 0
TIME_THRESHOLD = .1

def performHeavyComputation():
    print("performHeavyComputation() START")
    time.sleep(1 + random.random())
    print("performHavyComputation() END")

def callback_enter(e):
    global LAST_CALL_TIME
    global TIME_THRESHOLD

    t = time.time()
    if t - LAST_CALL_TIME < TIME_THRESHOLD:
        print("[%.3f] filtering event e:%s"%(t, e))
    else:
        LAST_CALL_TIME = t
        performHeavyComputation()
        t1 = time.time()
        TIME_THRESHOLD = t1 - t + 0.1

root.bind("<Return>", callback_enter)
root.mainloop()
  • It's working, thank you! I am just quite new to Python, can you give me a short explanation what global in this context does? – Natjo Dec 11 '16 at 17:25