Entering pan mode after embedding Matplotlib figure and toolbar into PySimpleGUI

Question:

Is there a way to programmatically enter Matplotlib’s pan mode, given that the figure is embedded into PySimpleGUI?
just like this

I’m basically looking for the equivalent of

fig.canvas.manager.toolbar.pan()

(which doesn’t seem to work with PySimpleGUI, as
fig.canvas.manager is None in that case).

Here is a simple code to embed Matplotlib into PySimpleGUI with the toolbar:

import matplotlib.pyplot as plt
import PySimpleGUI as sg
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk



"""----------------------------- matplotlib stuff -----------------------------"""
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
x_data = np.linspace(-42, 42, 300)
ax.plot(x_data, np.sin(x_data))



"""----------------------------- PySimpleGUI stuff -----------------------------"""
window_layout = [
    [sg.Canvas(key="-CANVAS_TOOLBAR-")],
    [sg.Canvas(key="-CANVAS_FIG-")]
]

window = sg.Window('Window', window_layout, resizable=True, finalize=True)



"""--------------------- embedding matplotlib into the GUI ---------------------"""
class Toolbar(NavigationToolbar2Tk):
    def __init__(self, *args, **kwargs):
        super(Toolbar, self).__init__(*args, **kwargs)

def draw_figure_w_toolbar(canvas_fig, canvas_toolbar, figure):
    figure_canvas_agg = FigureCanvasTkAgg(figure, canvas_fig)
    toolbar = Toolbar(figure_canvas_agg, canvas_toolbar)
    figure_canvas_agg.draw()
    toolbar.update()
    figure_canvas_agg.get_tk_widget().pack(side='top', fill='both', expand=True)
    return figure_canvas_agg

fig_agg = draw_figure_w_toolbar(window['-CANVAS_FIG-'].TKCanvas, window['-CANVAS_TOOLBAR-'].TKCanvas, fig)
# print(type(fig_agg))
# print(type(fig.canvas))



"""-------------------------- reading the GUI window --------------------------"""
while True:
    event, values = window.read()
    print("event", event, "nvalues", values)
    if event in (sg.WIN_CLOSED, "-ESCAPE-"):
        break

window.close()

I’ve looked at this question, but I wish to use Matplotlib’s toolbar.

Even this doesn’t work because plt.get_current_fig_manager() returns None in my case.

When printing type(fig_agg) from the code above, I get

<class 'matplotlib.backends.backend_tkagg.FigureCanvasTkAgg'>

which is also the type of fig.canvas.

By the way I thought about a trick to do it. Pressing p on the keyboard normally activates pan mode, so pressing the button programmatically does the trick! But that would be unethical cheating (:

Asked By: Username_22

||

Answers:

I found an answer to my question. In case it helps someone, the solution is simply

fig.canvas.toolbar.pan()

i.e. we remove manager from the original call mentioned above.

Answered By: Username_22