0
votes

I have a image i'm using in my GUI and i dont want it as an external resource when i compile the .exe or to my .py. I figured i should encode it to a string, copy the string in the code and decode it and serve it to Tkinter. Tried a bunch of solutions but still doesnt work, here is the code:

import tkinter as tk
from tkinter import filedialog
from tkinter import *
import PIL
from PIL import Image, ImageTk
import base64


stringimagine="something the print gave me"


imagine=open('logo.jpg','rb')
encoded=base64.b64encode(imagine.read())
print(encoded)
imagine2=base64.b64decode(stringimagine)


fereastra_principala = tk.Tk()



poza=Label(fereastra_principala,image=imagine2)
poza.pack(fill='both',expand='yes')

fereastra_principala.mainloop()

to this code i receive this error:

File "C:\Python34\lib\tkinter\__init__.py", line 2609, in __init__ Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Python34\lib\tkinter\__init__.py", line 2127, in __init__ (widgetName, self._w) + extra + self._options(cnf))_tkinter.TclError

And this is how i use to get the photo now, as an external resource:

img=Image.open('logo.jpg')
image=ImageTk.PhotoImage(img)
poza=Label(fereastra_principala,image=image)
poza.pack()
2

2 Answers

1
votes

If you have base64-encoded data, you need to use the data argument. However, I don't think this will work for jpg. It will work for .gif images though.

This is what the canonical documentation says for the data option:

Specifies the contents of the image as a string. The string should contain binary data or, for some formats, base64-encoded data (this is currently guaranteed to be supported for GIF images). The format of the string must be one of those for which there is an image file format handler that will accept string data. If both the -data and -file options are specified, the -file option takes precedence.

Example

import Tkinter as tk

IMAGE_DATA = '''
    R0lGODlhEAAQALMAAAAAAP//AP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAA\nAAAAACH5BAEAAAIALAAAAAAQABAAQAQ3UMgpAKC4hm13uJnWgR
    TgceZJllw4pd2Xpagq0WfeYrD7\n2i5Yb+aJyVhFHAmnazE/z4tlSq0KIgA7\n
    '''

root = tk.Tk()
image = tk.PhotoImage(data=IMAGE_DATA)
label = tk.Label(root, image=image, padx=20, pady=20)
label.pack()

root.mainloop()
0
votes

Got a way:

Say image='abc' is the string of the image coded in b64.

def install():
    if not os.path.isfile("logo.jpg"):
        open('logo.jpg','wb').write(base64.b64decode(image))

Gonna run this in my main() function and if the image doesnt exist in the folder, it will be created. Afterwords you'll just load the image as normal:

self.img=Image.open('logo.jpg')
self.image=ImageTk.PhotoImage(self.img)

I havent found a solution not to save the image at all however.