Force redraw() / redraw with callback

I have a p5py application that requires getting data from the internet on user input. I’m running the sketch with no_loop() in the setup as animation is only required on user input.

Fetching and processing the data can take a second, but the user input is available immediately and I would like to draw it to the screen right away, then do the fetching and processing.

The following code is inside of key_pressed(), which keeps track of user input in the object user_input

    if key == 'ENTER':
        # assign the global variable text_to_display to whatever the user typed
        text_to_display = user_input
        # call draw to render that text to screen
        redraw()
        # get and process data from the input
        get_and_process(user_input)

I would expect redraw to execute before get_and_process is called, but that’s not happening. I see the redrawn results only after get_and_process is complete.

Maybe something analogous to p5’s request animation frame step is happening. Is there a way for me to force redraw to execute before the program moves on? Or to call get_and_process as a callback on redraw()?

Disclaimer: I know nothing about async techniques and threads in Python.

It seems that the entire key_pressed() block must complete before the next frame can redraw. Maybe you could use a thread? Something like –

from p5 import *
import threading

def setup():
    size(500, 500)
    no_loop()

def draw():
    background(0)
    text(str(frame_count), 10, 10)

def key_pressed(e):
    worker = threading.Thread(target=print_frame_count)
    worker.start()
    redraw()

def print_frame_count():
    time.sleep(2)
    print(frame_count)

run()

The frame number is drawn in the display window two seconds before it appears in the console.

2 Likes

That did the trick. Thanks a bunch!

2 Likes