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.

wowwee
  • 176
  • 1
  • 2
  • 12
  • So you want to display an image in a GUI? Why do you want it as a string? – Felix Jun 28 '18 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? – wowwee Jun 28 '18 at 18:24
  • Ok now I get it. What are you using to freeze your program? pyinstaller? – Felix Jun 28 '18 at 18:31
  • @Felix Yep yep, pyinstaller. – wowwee Jun 28 '18 at 18:37
  • Possible duplicate of [Pyinstaller and --onefile: How to include an image in the exe file](https://stackoverflow.com/questions/31836104/pyinstaller-and-onefile-how-to-include-an-image-in-the-exe-file) – Felix Jun 28 '18 at 18:39
  • @Felix See I've read that question and many others like it but I don't understand what it is he really did, he posted what changes he made. But not what those changes do specifically, I'd like to understand what it is id be doing, you know? – wowwee Jun 28 '18 at 18:51

1 Answers1

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()
figbeam
  • 7,001
  • 2
  • 12
  • 18
  • 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. – wowwee Jun 28 '18 at 18:46
  • Try with a couple of different images. Tkinter PhotoImage does not recognize all image formats. – figbeam Jun 28 '18 at 23:02