Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
696 views
in Technique[技术] by (71.8m points)

python - Base64 string to image in tkinter

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:Python34libkinter\__init__.py", line 2609, in __init__ Widget.__init__(self, master, 'label', cnf, kw)
File "C:Python34libkinter\__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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
AAAAACH5BAEAAAIALAAAAAAQABAAQAQ3UMgpAKC4hm13uJnWgR
    TgceZJllw4pd2Xpagq0WfeYrD7
2i5Yb+aJyVhFHAmnazE/z4tlSq0KIgA7

    '''

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

root.mainloop()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...