user2242044
user2242044

Reputation: 9213

how to remove gray border around matplotlib plots in Tkinter canvas

How can I remove the gray border that appears around each canvas? I am already setting the facecolor to black which I thought should take care of it.

import matplotlib
matplotlib.use('TkAgg')

from numpy import arange, sin, cos, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure

import sys
if sys.version_info[0] < 3:
    import Tkinter as Tk
else:
    import tkinter as Tk

root = Tk.Tk()
root.configure(background='black')
x = Figure(figsize=(3,3), dpi=100, facecolor='black')

b = x.add_subplot(111,  axisbg='#1a1a1a')
c = arange(0.0,3.0,0.01)
s = cos(2*pi*c)
b.plot(c,s)

f = Figure(figsize=(5,3), dpi=100, facecolor='black')
a = f.add_subplot(111,  axisbg='#1a1a1a')
t = arange(0.0,3.0,0.01)
s = sin(2*pi*t)
a.plot(t,s)


canvas = FigureCanvasTkAgg(f, master=root)
canvas1 = FigureCanvasTkAgg(f, master=root)
canvas.show()
canvas.get_tk_widget().grid(row=0,column=0)
canvas1.show()
canvas1.get_tk_widget().grid(row=1,column=0)

Tk.mainloop()

Upvotes: 0

Views: 3956

Answers (1)

Jakob
Jakob

Reputation: 20811

The gray border around the canvas you see is the background of the FigureCanvasTkAgg widget. So besides changing the background of the root and Figure background you have to change the canvas background as well.

To change the background of the FigureCanvasTkAgg you have to get the underlying Tk canvas widget and configure it appropriately. The required method is documented here.

Hence, you have to adapt your code like

...
canvas = FigureCanvasTkAgg(f, master=root)
canvas.get_tk_widget().configure(background='black',  highlightcolor='black', highlightbackground='black')
canvas1 = FigureCanvasTkAgg(f, master=root)
canvas1.get_tk_widget().configure(background='black', highlightcolor='black', highlightbackground='black')
canvas.show()
canvas.get_tk_widget().grid(row=0,column=0)
canvas1.show()
canvas1.get_tk_widget().grid(row=1,column=0)
...

Update:

If there remains a small gray border, this might be due to the current focus of one of the canvases. With my test the upper canvas still has a small gray border, which indicates that the other canvas is on focus (highlighted with a black border). Hence, to get rid of this additional border the highlight color of the not focused canvas has to be changed. This can be achieved with the two argumentshighlightbackground and highlightcolor. I've updated the code posted above to account for this issue. With this the window looks on my machine like
enter image description here

Upvotes: 2

Related Questions