1

So I have this basic code at the moment.

import base64
with open("test.png", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())

And it converts the image into a crazy long string, I'm doing this of hopes of copying that string and making it a variable in another script I'm making. I don't want to save it to the computer or anything, I just want it to be decoded and opened for the GUI background. I'm trying to make it so just the exe is needed and nothing else.

I've found other questions going over this, but sadly I can't quite understand the answers very well. So if possible the simplest way would be much preferred, thank you!

Edit: The possible duplicate that was linked is fair, but it doesn't answer my question because as I said I don't understand what they did, why it works that way. And if i understand it at all I think it stores the image path but not the actual image in the exe. I want to be able to take the exe file and only that on a flash drive and it works.

6
  • So you want to display an image in a GUI? Why do you want it as a string? Commented Jun 28, 2018 at 18:20
  • @Felix I just want it to be stored in the exe file, so you only need that one file. And the best way I can tell from others posts is to encode the image with base64, save that string as a variable. Then decode that string. Right? Commented Jun 28, 2018 at 18:24
  • Ok now I get it. What are you using to freeze your program? pyinstaller? Commented Jun 28, 2018 at 18:31
  • @Felix Yep yep, pyinstaller. Commented Jun 28, 2018 at 18:37
  • Possible duplicate of Pyinstaller and --onefile: How to include an image in the exe file Commented Jun 28, 2018 at 18:39

1 Answer 1

1

You can print the encoded_string to the console, copy it from there and paste it into your code. The encoded_string will look something like:

'R0lGODlhUABFAHAAA ... Qiq0Z1q2XN6oYYoQIBAQA7'

Use it in code like this example:

import tkinter as tk

image_string = 'R0lGODlhUABFAHAAA ... Qiq0Z1q2XN6oYYoQIBAQA7'

root = tk.Tk()
imgFrame = tk.Frame(root)
imgFrame.pack()
img = tk.PhotoImage(data=image_string)
imgLabel = tk.Label(imgFrame, image=img)
imgLabel.pack()
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks this is exactly what I'm looking for, but sadly when I ran it I got a _tkinter.TclError: couldn't recognize image data error.
Try with a couple of different images. Tkinter PhotoImage does not recognize all image formats.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.