Optimize the process of importing multiple images from the internet, tkinter

Viewed 18


I'm writing a recipe program and as part of it, I want to make a series of buttons with different images (for each recipe). I am using the Edamam recipe search api (here) which gives me urls to all the images I need.

The way I my code operates is as follows:

for each recipe:
   data = urlopen(image_url)
   image = ImageTk.PhotoImage(data=data.read())  # Convert to a tkinter PhotoImage object
   b = Button(root, command = lambda i=recipe_url:callback(i), image = image)  # callback() opens the webpage for a given url
   b.image = image  # To prevent garbage collection from removing the image
   b.pack()

Obviously this is a simplified version and I've removed or renamed things for it to make sense without looking at the entire program. However, it addresses the performance issue which is the process of downloading and converting images.

The relevant information I can think of is:

  • 20 images need to be converted each time
  • It takes around 18 seconds for the entire process to run
  • I am using the smallest sized images available (sizes of large, medium, small, and thumbnail are available)
  • The relevant modules I'm using are PIL, urllib, and tkinter

My question is how can I increase the speed of this component without compromising on functionality.

Let me know if there's any other information I need to add and thank you in advance for the help.

1 Answers

Thanks to @Alexander for the tip off on multiprocessing, I tried implementing it but I couldn't really wrap my head around it, so I used multithreading instead and now it is far more efficient. Each thread contains the code for one button and then the loop simply defines and then starts the threads:

x = threading.Thread(target=image_conversion, args=(item,))
x.start()
Related