0

As a bit of a background, I picked up a project from another developer who wrote the entire as one big file that runs from top to bottom.

The manager wants to display images / videos on the screen at certain points during the scripts execution and that disappear during other points of execution.

I have worked with Tk extensively, but I am still limited by the lack of thread safeness and its blocking mainloop() function.


Is there a way in python to display images / videos asynchronously/ in a non blocking way, while the main thread still executes? In the context of this project, the API would have to be something similar to what is below.

if __name__ == "__main__":
    gui = load_gui()
    
    gui.display_image("doing_math.png") #doesn't block
    for i in range(0, 500):
        print(str(i))
        
    gui.display_image("math_complete.mp4")#doesn't block
    sleep(2)
    gui.clear_display()

currently I am using trying to use Tk like displayed below. but it is limited by the mainloop() blocking the rest of the scripts execution.

class MediaGui(tk.Tk):
    def __init__(self):
        self.mainloop()
    ...

gui = MediaGui() #this line blocks because of mainloop
gui.load_image("image.png")
Bigbob556677
  • 1,805
  • 1
  • 13
  • 38

1 Answers1

0

Try this :

from concurrent.futures import ThreadPoolExecutor

gui = load_gui()

def run_io_tasks_in_parallel(tasks):
    with ThreadPoolExecutor() as executor:
        running_tasks = [executor.submit(task) for task in tasks]
        for running_task in running_tasks:
            running_task.result()

run_io_tasks_in_parallel([
    lambda:  gui.display_image("doing_math.png"),
    lambda: gui.display_image("math_complete.mp4"),
])
abdou_dev
  • 805
  • 1
  • 10
  • 28
  • I have tried offloading everything to threads but the problem is that I can't get the reference to the actual Tk object passed back to the main thread. Im thinking Tk isn't the way to go with it. Thanks for your answer! (note my edit) – Bigbob556677 Oct 19 '21 at 13:27
  • Did you see this ? https://stackoverflow.com/questions/16745507/tkinter-how-to-use-threads-to-preventing-main-event-loop-from-freezing I think that this link will help you – abdou_dev Oct 19 '21 at 13:31