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.
JavaScript
x
30
30
1
import tkinter
2
from matplotlib.backends.backend_tkagg import (
3
FigureCanvasTkAgg, NavigationToolbar2Tk)
4
from matplotlib.figure import Figure
5
import numpy as np
6
7
root = tkinter.Tk()
8
root.wm_title("Embedding in Tk")
9
10
fig = Figure(figsize=(5, 4), dpi=100)
11
t = np.arange(0, 3, .01)
12
fig.add_subplot().plot(t, 2 * np.sin(2 * np.pi * t))
13
14
canvas = FigureCanvasTkAgg(fig, master=root) # A tk.DrawingArea.
15
canvas.draw()
16
17
color = "#d469a3"
18
toolbar = NavigationToolbar2Tk(canvas, root, pack_toolbar=False)
19
toolbar.config(background=color)
20
toolbar._message_label.config(background=color)
21
toolbar.update()
22
23
button = tkinter.Button(master=root, text="Quit", command=root.quit)
24
25
button.pack(side=tkinter.BOTTOM)
26
toolbar.pack(side=tkinter.BOTTOM)
27
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
28
29
tkinter.mainloop()
30
This gives me the window:
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
:
JavaScript
1
4
1
print (toolbar.winfo_children()[-2])
2
3
# .!navigationtoolbar2tk.!label
4
And to change its color:
JavaScript
1
2
1
toolbar.winfo_children()[-2].config(background=color)
2