Error: 'Fail to create pixmap with Tk_GetPixmap in TkImgPhotoInstanceSetSize' when executing plt.subplots()

Question:

When i executing this function i get this error: Fail to create pixmap with Tk_GetPixmap in TkImgPhotoInstanceSetSize. This error occur in this line: fig, ax = plt.subplots()(line 12). The strange thing is, that this error only occur sometimes (Maybe only 10% of their executes).
Here is my whole function:

from bs4 import BeautifulSoup
from PIL import ImageDraw, Image, ImageFont
from colour import Color
import base64
from io import BytesIO
import matplotlib.pyplot as plt

def getCurrentBatterySOCImage(batterySOC):
   red = Color("red")
   colors = list(red.range_to(Color("#23b818"), 101))
   color = colors[round(batterySOC)].hex
   fig, ax = plt.subplots(facecolor="black")
   ax.set_facecolor("black")
   fig.tight_layout()
   ax.axis("off")
   ax.bar([1], batterySOC, color=color)
   ax.axis([0.6,1.4,0,100])
   ax.set_aspect(.02)

   tmpfile = BytesIO()
   fig.savefig(tmpfile, format="png", pad_inches=0, bbox_inches="tight")
   plt.close(fig)

   bar = Image.open(tmpfile)
   bar = bar.resize((107, 208))
   img = Image.new("RGBA", (136, 248), (255, 0, 0, 0))
   img.paste(bar, (14, 26), bar)
   battery = Image.open("img/battery.png")

   img.paste(battery, (0, 0), battery)


   font = ImageFont.truetype('font/RobotoMono.ttf', 40)
   message = f"{batterySOC}%"

   draw = ImageDraw.Draw(img)
   w, h = draw.textsize(message, font=font)

   draw.text(((136-w)/2, (248-h)/2), f"{batterySOC}%", fill=(255, 255, 255), font=font, stroke_width=2, stroke_fill="black")

   tmpfile1 = BytesIO()
   img.save(tmpfile1, format="png")
   encoded = base64.b64encode(tmpfile1.getvalue()).decode('utf-8')

   with open("index.html") as fp:
       soup = BeautifulSoup(fp, "html.parser")
       soup.find("img", attrs={'id': 'battery'})['src'] = f"data:image/png;base64,{encoded}"
   with open("index.html", "w") as fp:
       fp.write(soup.decode())
   return

Can someone help me to fix this?

Asked By: monkaCode

||

Answers:

This seems to be a memory issue from this issue, new in Matplotlib 3.5 (vs 3.3)

The recommended way is to switch to ‘Agg’ backend if possible

Answered By: PiWi
#Have the following versions: python v3.8.13 + matplotlib v3.5.2
#First I also got the error, then I extended the code like this:

import matplotlib.pyplot as plt
...
isShowChart=False
...
...
if isShowChart == True:
  #Variant 1: Show chart + wait for user until graphic clicks away again
  plt.show()
else:
  #Variant 2: Save the chart image in the file system .. for automated processing
  import matplotlib
  matplotlib.use('Agg')
  plt.savefig(namePic.png, format="png") #default=jpg

print(">>> done <<<")
Answered By: Sten
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.