0

Long story short: I want to draw an image in a tkinter.Canvas on a button click. Obviously, this will happen after calling mainloop(). However, create_image() function is not updating the canvas.

Long Story: I'm trying to draw several images in a tkinter.Canvas on a button click. This is roughly my code.

from PIL import Image
from PIL.ImageTk import PhotoImage


# this code is inside an event handler of a button click
# this is also a class-method
ROW_COUNT = 1
COL_COUNT = 3
for i in range(ROW_COUNT):
    for j in range(COL_COUNT):
        raw_img = Image.open(img_list[i * COL_COUNT + j])
        resized_img = raw_img.resize((160, 160), Image.ANTIALIAS)
        img = PhotoImage(resized_img)
        x = j * 170
        y = i * 170
        self.canvas.create_image(x, y, anchor=NW, image=img)
        self.canvas.update_idletasks()

As this code executes on a button click, this will surely be after calling mainloop(). However, nothing happens after the execution of this code. If I recall mainloop() after the loops, only the last image gets drawn. If I call mainloop() in the inner loop, only the first image gets drawn (and probably both the loops breaks).

How can I draw all the images?

Parvez M Robin
  • 154
  • 1
  • 3
  • 16
  • I don't see any code where you actually draw something. Oh yea; the code doesn't run. Please provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – figbeam Aug 25 '18 at 19:35
  • Sorry, did I misunderstand completely? You want to initiate an action after mainloop has started? In that case you should use `bind`. Check out [Events and Bindings](http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm) and then google for examples. – figbeam Aug 25 '18 at 20:01
  • You need to save references to the images you are creating - otherwise, they get garbage collected and vanish from your widget. Appending them to a global list would be a reasonable solution here, assuming that the images will remain through the rest of the program's execution. – jasonharper Aug 25 '18 at 21:00

0 Answers0