On 2016-08-13 02:40, huey.y.ji...@gmail.com wrote:
Hi All,
Image display drives me crazy. After I get it displayed, and want to do the job
with a class, display failed again. Please take a look at my trial code:
from Tkinter import *
class imageDisplay:
def __init__(self, parent=None):
canvas = Canvas(width=400, height=300, bg='beige')
canvas.pack()
self.canvas = canvas
img = PhotoImage(file="xxx.gif")
self.canvas.create_image(150, 0, image=img, anchor=NW)
if __name__ == '__main__':
imageDisplay()
mainloop()
Result: A blank canvas was displayed. No error message.
Can somebody help? Thanks so much!
You need to keep a reference to the image, so add:
self.img = img
otherwise, when __init__ returns, it'll be garbage-collected.
You also need to keep a reference to the instance created by
imageDisplay(), so:
display = imageDisplay()
This is because the internals of tkinter is actually written in Tcl
(another programming language), so although Tcl might have a reference
to the window you're seeing, Python itself won't. (Why Tcl maintains a
reference to the window, but not the image that's in the window, is a
mystery... :-))
--
https://mail.python.org/mailman/listinfo/python-list