Request Help With Displaying XBM Image
Peter Otten
__peter__ at web.de
Fri Feb 26 16:49:58 EST 2016
Wildman via Python-list wrote:
> As part of a program I am working on I want to display a
> 48x48 XBM image on the main window. I have done a lot
> of searching for code snippets and I found what appears
> to be the correct way to do it using a Label. So far I
> have not been able to get it to work. I have tried
> different variations of the syntax but nothing will
> display the image. The Label will expand to size of
> the image but nothing is there. I have the background
> of the Label set to white so it can be seen.
>
> For experimentation I create a small program for the
> sole purpose of displaying an XBM image. The complete
> script is pasted below. I am thinking the problem
> might have something with the way the image object
> is being created. I'm probable making a dumb newbie
> mistake. BTW, if I run the script from a terminal
> window, I do not get any errors. Any guidance is
> appreciated.
It's not you, the program as you wrote it should and would show the image,
were it not for an odd quirk in how images are handled in tkinter:
You have to keep an explicit reference of the Image to prevent it from being
garbage-collected. Changing open_image() as follows
> def open_image(self):
> file_filter = [
> ('X BitMap', '*.xbm *.XBM'),
> ('all files', '*.*')
> ]
> fileName = tkFileDialog.askopenfilename(parent=root,
> initialdir=cv.default_dir,
> filetypes=file_filter,
> title="Open XBM Image")
> if fileName:
> cv.default_dir = os.path.dirname(fileName)
> openImage = Image.open(fileName)
self.imageFile = ImageTk.BitmapImage(openImage)
self.xbmImage.config(image=self.imageFile)
> else:
> return None
should achieve that.
More information about the Python-list
mailing list