Reputation: 171
I would like to decode a string in base64
into an image for my canvas background. I know that I can create an empty image file and write to it using this code:
fh = open("background.png", "wb")
fh.write(base64.b64decode(background_image.background_image))
fh.close()
But I want to insert the image directly into the canvas background wihout creating any extra files like so:
background_image = base64.b64decode(background_image.background_image)
background_image = ImageTk.PhotoImage(file=background_image)
canvas.create_image(0, 0, image=background_image, anchor=NW)
But I get the following error.
AtrributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
Upvotes: 0
Views: 129
Reputation:
If you are using data in memory, instead of a file, then it should be data=background_image
try:
import Tkinter as tk ## Python 2.x
except ImportError:
import tkinter as tk ## Python 3.x
grape_gif='''\
R0lGODlhIAAgALMAAAAAAAAAgHCAkC6LV76+vvXeswD/ANzc3DLNMubm+v/6zS9PT6Ai8P8A////
/////yH5BAEAAAkALAAAAAAgACAAAAS00MlJq7046803AF3ofAYYfh8GIEvpoUZcmtOKAO5rLMva
0rYVKqX5IEq3XDAZo1GGiOhw5rtJc09cVGo7orYwYtYo3d4+DBxJWuSCAQ30+vNTGcxnOIARj3eT
YhJDQ3woDGl7foNiKBV7aYeEkHEignKFkk4ciYaImJqbkZ+PjZUjaJOElKanqJyRrJyZgSKkokOs
NYa2q7mcirC5I5FofsK6hcHHgsSgx4a9yzXK0rrV19gRADs=
'''
master=tk.Tk()
master.geometry("100x100")
photo=tk.PhotoImage(data=grape_gif)
canvas=tk.Canvas(master)
canvas.grid()
canvas.create_image(0, 0, image=photo, anchor="nw")
master.mainloop()
Upvotes: 1