Thursday, July 15, 2010

python-tk: tkinter photo doesn't work inside a function

Wow, python-tk sucks. When I create the photo inside a function, it gets garbage-collected because it's not smart enough to know that the label is using it. So I have to manually keep it from being deallocated (in this case, by making it global). Also, I'd really like to use after_idle instead of after, but it never gets around to actually updating the display.

#!/usr/bin/python

import Tkinter
import ImageTk,Image

root = Tkinter.Tk()
root.geometry('+640+480')

old_label = None
label = None
photo = None
def display_image(root, image):
global old_label
global label
global photo

root.geometry('%dx%d' % (image.size[0], image.size[1]))

photo = ImageTk.PhotoImage(image)

label = Tkinter.Label(root, image=photo)
label.place(x=0,y=0,width=image.size[0],height=image.size[1])

if old_label is not None:
old_label.destroy()

old_label = label

def image_loop():
global root
print '.'
image = get_image()
display_image(root, image)
root.after(1000,image_loop)

image_loop()

root.mainloop()

No comments: