3

The code below illustrates a buffer which displays with pygame.image.frombuffer but not with tkinter PhotoImage

import chess, chess.svg, pylunasvg as pl
from tkinter import Tk, PhotoImage

# This is where I create the buffer
board = chess.Board(chess.STARTING_FEN)
svg_text = chess.svg.board(board, size=400)
document = pl.Document.loadFromData(svg_text)
byts = bytes(document.renderToBitmap())

#Now that I have this raster buffer 'byts'
surf = pygame.image.frombuffer(byt, (400, 400), 'RGBA') #works

root = Tk()
PhotoImage(data=byt) #raises an error about the image

I know this is as a result of something I don't know about tkinter. I would really appreciate that you point out what is wrong and what I can do. Thanks in advance

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Alphonsus
  • 73
  • 6
  • Why do you think it should work? The argument must be either a file path or a PLI image. See [Tkinter PhotoImage](https://www.pythontutorial.net/tkinter/tkinter-photoimage/). – Rabbid76 Jul 24 '22 at 06:00
  • I have also tried it with a PIL Image. That was my first try – Alphonsus Jul 24 '22 at 06:24

1 Answers1

3

PhotoImage's argument must be a file path. However, there is a solution using a PLI image. See Tkinter PhotoImage. Make a PLI image form the buffer and use that image to create an ImageTk.PhotoImage object:

from PIL import Image, ImageTk
image = Image.frombytes('RGBA', (400, 400), byt, 'raw')

root = Tk()
photo_image = ImageTk.PhotoImage(image)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174