imagepython-2.7tkinter

How to use XBM image data in Python without referencing external file


Apologies if this is a duplicate; I've been searching with every combination of keywords I can think of but I can't find an article that addresses this.

I'm building a Python Tkinter application (Python 2.7.x, Win 7) which includes buttons with image data (drawn from XBM files). For example,

self._ResetIcon  = tk.BitmapImage(file='ResetIcon.xbm')
self._Reset      = tk.Button(self,
                             width=20, height=20,
                             image=self._ResetIcon,
                             command=self._reset)

Now I'm 99.9% sure there's a way to include the XBM image data as a declaration of some kind directly in the Python module itself, rather than pulling it from the external file. But I can't find anything online that describes how to do it.

Is there a way to do this?


Solution

  • Did some more digging via Google and found it.

    http://effbot.org/tkinterbook/bitmapimage.htm(Internet Archive)

    An X11 bitmap image consists of a C fragment that defines a width, a height, and a data array containing the bitmap. To embed a bitmap in a Python program, you can put it inside a triple-quoted string:

    BITMAP = """
    #define im_width 32
    #define im_height 32
    static char im_bits[] = {
    0xaf,0x6d,0xeb,0xd6,0x55,0xdb,0xb6,0x2f,
    0xaf,0xaa,0x6a,0x6d,0x55,0x7b,0xd7,0x1b,
    0xad,0xd6,0xb5,0xae,0xad,0x55,0x6f,0x05,
    0xad,0xba,0xab,0xd6,0xaa,0xd5,0x5f,0x93,
    0xad,0x76,0x7d,0x67,0x5a,0xd5,0xd7,0xa3,
    0xad,0xbd,0xfe,0xea,0x5a,0xab,0x69,0xb3,
    0xad,0x55,0xde,0xd8,0x2e,0x2b,0xb5,0x6a,
    0x69,0x4b,0x3f,0xb4,0x9e,0x92,0xb5,0xed,
    0xd5,0xca,0x9c,0xb4,0x5a,0xa1,0x2a,0x6d,
    0xad,0x6c,0x5f,0xda,0x2c,0x91,0xbb,0xf6,
    0xad,0xaa,0x96,0xaa,0x5a,0xca,0x9d,0xfe,
    0x2c,0xa5,0x2a,0xd3,0x9a,0x8a,0x4f,0xfd,
    0x2c,0x25,0x4a,0x6b,0x4d,0x45,0x9f,0xba,
    0x1a,0xaa,0x7a,0xb5,0xaa,0x44,0x6b,0x5b,
    0x1a,0x55,0xfd,0x5e,0x4e,0xa2,0x6b,0x59,
    0x9a,0xa4,0xde,0x4a,0x4a,0xd2,0xf5,0xaa
    };
    """
    

    To create X11 bitmaps, you can use the X11 bitmap editor provided with most Unix systems, or draw your image in some other drawing program and convert it to a bitmap using e.g. the Python Imaging Library.

    The BitmapImage class can read X11 bitmaps from strings or text files:

    bitmap = BitmapImage(data=BITMAP)
    bitmap = BitmapImage(file="bitmap.xbm")