[Tkinter-discuss] refreshing images

Michael Lange klappnase at web.de
Thu May 6 11:52:11 CEST 2010


Hi Mark,

On Wed, 5 May 2010 13:35:30 -0400
Mark Peterson <markpete at gmx.com> wrote:

> Hi, all.  I'm brand new to using Tkinter, and was hoping to get a tip
> on getting images to refresh after pressing a button.  The complete
> code I'm using is below.
> 
> Basically, when I click on the "Next image" button, it will delete the
> original image (good) but the next image doesn't show up (bad).  Is
> there a command that gets the canvas to redraw with the second image?
> 
> Since I'm very new to Tkinter, the more explicit you could be about
> how to change the code, the more helpful it would be.  Thanks very
> much for any help.
> 

The problem with your code is that you forget to keep a reference to
the newly created PhotoImage object, so when the nextImage() function
is done, the photo will immediately be garbage collected. Adding a
"global photo" statement to nextImage() fixes this.
Besides this, there is no need to make cnvas and item global in
nextImage() and it is probably better to simply change the image of the
existing canvas image item instead of creating a new one, so a better
nextImage() func might look like:

def nextImage():
    global photo
    im = Image.open("image2.gif")
    photo = ImageTk.PhotoImage(im)
    canvas.itemconfigure(item, image=photo)

Another thing: I see you use gif images in your example; because you
say you are new to Tkinter I am not sure if you know taht if you only
need to display gif images you can use the PhotoImage class built into
Tkinter which would make changing the image even easier:

def nextImage():
    photo.configure(file='image2.gif')

The ImageTk.PhotoImage does not have a configure() method, but you need
it only if you want to display image formats other than gif.

I hope this helps

Michael

> Best,
>    Mark
> 
> def nextImage():
> 
>     global canvas
>     global item
> 
>     canvas.delete(item)
> 
>     im = Image.open("image2.gif")
>     photo = ImageTk.PhotoImage(im)
>     item = canvas.create_image(10,10,anchor=NW, image=photo)
> 
> 
> from Tkinter import *
> import Image
> import ImageTk
> 
> root = Tk()
> 
> im = Image.open("image1.gif")
> canvas = Canvas(root, height=im.size[1]+20, width=im.size[0]+20)
> canvas.pack(side=LEFT,fill=BOTH,expand=1)
> 
> photo = ImageTk.PhotoImage(im)
> item = canvas.create_image(10,10,anchor=NW, image=photo)
> 
> b1 = Button(root, text="Next image", width=15, command=nextImage)
> b1.pack()
> 
> mainloop()
> _______________________________________________
> Tkinter-discuss mailing list
> Tkinter-discuss at python.org
> http://mail.python.org/mailman/listinfo/tkinter-discuss


More information about the Tkinter-discuss mailing list