0

I need to save an image of a chessboard, like the one created by this code:

import chess
board = chess.Board()
board

The output is the starting chessboard:

chessboard

How can I save this image and print it (for example inside a function)? Is there a unique package for these things in python? If I try to print the board (typing print (board)) I get a string that presents the chessboard, not the same photo.

Eliahu Aaron
  • 4,103
  • 5
  • 27
  • 37
  • You can use `dir(board)` to see the available fields/methods on your chess board. Maybe there's something there to save an image or get its representation in bytes, which could then be written to disk? – byxor Mar 03 '20 at 12:58
  • check source code to see what module it uses. For most GUI frameworks you can write code which gets pixels from "canvas" in window and you can write it in file. Problem can be with `Tkinter`. – furas Mar 03 '20 at 13:05
  • BTW: you can try to use some module to take screenshot. ie.[pyscreenshot](https://pypi.org/project/pyscreenshot/), [PyAutoGUI](https://pyautogui.readthedocs.io/en/latest/screenshot.html), [mss](https://github.com/BoboTiG/python-mss). See: [Get screenshot on Windows with Python?](https://stackoverflow.com/questions/2846947/get-screenshot-on-windows-with-python) – furas Mar 03 '20 at 13:08

2 Answers2

3

You can use sys to write the output into an svg file and then save it. First use chess.svg to create the svg file of chess board and then assign svg in some variable and write that data in the file.

import sys
import chess.svg
import chess
board = chess.Board()
boardsvg = chess.svg.board()
outputfile = open('name.svg', "w")
outputfile.write(boardsvg)
outputfile.close()

I hope that helps!

Naazneen Jatu
  • 526
  • 9
  • 19
  • 1
    *"output into an svg/png file"* - might elaborate on this? As far as I know, the `chess` library doesn't enable an output to `.png`. The only option might be converting it afterwards, though I deem that to be pretty inefficient. – J. M. Arnold Jan 05 '21 at 15:51
  • 1
    Thanks for the catch. Let me make an edit here. – Naazneen Jatu Jan 06 '21 at 16:32
2

you have to write chess.svg.board(board = board) other whise you will have an empty board