In a GTK application using matplotlib, how can I set the color that appears while the figure is being redrawn after a window resize?

Viewed 85

I can embed a matplotlib figure in a GTK application by following some of the examples, like this one in the matplotlib documentation. However, when I resize the application window, there is a flicker of white as the figure is being redrawn.

This isn't that much of a problem if the figure I am going to show also has a white background. But if I am using a dark figure style (i.e. to match the appearance of the rest of my application), there is always a white flicker until the figure is drawn in the correct style. This is somewhat jarring if the rest of the application is using a darker theme.

Is there a way I can control the background that is shown by a matplotlib backend while the figure is being drawn?

If I could set the color that appears while drawing, there would still be a flickering effect of the data and axes of the plot being redrawn, but at least the background would stay the same color before and after the figure is drawn.

To illustrate the unwanted effect, if I add a dark plot style to the example linked above, each time I resize the window I can see the white flicker.

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

from matplotlib.backends.backend_gtk3agg import (
    FigureCanvasGTK3Agg as FigureCanvas)
from matplotlib.figure import Figure
import numpy as np
import matplotlib.pyplot as plt

plt.style.use('dark_background')      # use the dark style so flicker is more apparent

win = Gtk.Window()
win.connect("delete-event", Gtk.main_quit)
win.set_default_size(400, 300)
win.set_title("Embedding in GTK")

fig = Figure(figsize=(5, 4), dpi=100)
ax = fig.add_subplot()
t = np.arange(0.0, 3.0, 0.01)
s = np.sin(2*np.pi*t)
ax.plot(t, s)

sw = Gtk.ScrolledWindow()
win.add(sw)
# A scrolled window border goes outside the scrollbars and viewport
sw.set_border_width(10)

canvas = FigureCanvas(fig)  # a Gtk.DrawingArea
canvas.set_size_request(800, 600)
sw.add(canvas)

win.show_all()
Gtk.main()

(Resizing the window to very small sizes doesn't cause the flickering, presumably because once the figure is drawn at the smallest size, it does not get redrawn, just clipped.)

I'm using GTK 3, matplotlib 3.4.3, and Python 3.8.10 on Ubuntu.

0 Answers
Related