Skip to content
Advertisement

How to change color of matplotlib toolbar in tkinter?

I would like to change the color of the toolbar when making a matplotlib figure in tkinter. I have managed to find and change the color of two parts. There is one remaining.

My code comes directly from https://matplotlib.org/stable/gallery/user_interfaces/embedding_in_tk_sgskip.html?highlight=embedding%20tk with three additional lines to change colors.

import tkinter
from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.figure import Figure
import numpy as np

root = tkinter.Tk()
root.wm_title("Embedding in Tk")

fig = Figure(figsize=(5, 4), dpi=100)
t = np.arange(0, 3, .01)
fig.add_subplot().plot(t, 2 * np.sin(2 * np.pi * t))

canvas = FigureCanvasTkAgg(fig, master=root)  # A tk.DrawingArea.
canvas.draw()

color = "#d469a3"
toolbar = NavigationToolbar2Tk(canvas, root, pack_toolbar=False)
toolbar.config(background=color)
toolbar._message_label.config(background=color)
toolbar.update()

button = tkinter.Button(master=root, text="Quit", command=root.quit)

button.pack(side=tkinter.BOTTOM)
toolbar.pack(side=tkinter.BOTTOM)
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)

tkinter.mainloop()

This gives me the window:

Plot window with the bit I still want to change pointed out

What is the small, grey rectangle I have pointed out? How do I change its color?

Advertisement

Answer

It is an empty label. You can get a reference to it via winfo_children:

print (toolbar.winfo_children()[-2])

# .!navigationtoolbar2tk.!label

And to change its color:

toolbar.winfo_children()[-2].config(background=color)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement