将Matplotlib图形和工具条嵌入PySimpleGUI后进入平移模式

92dk7w1h  于 2023-01-26  发布在  其他
关注(0)|答案(1)|浏览(120)

如果图形嵌入到PySimpleGUI中,是否有方法以编程方式进入Matplotlib的平移模式?just like this
我基本上是在寻找

fig.canvas.manager.toolbar.pan()

(这似乎不适用于PySimpleGUI,因为fig.canvas.manager在这种情况下是None)。
下面是一段简单的代码,可以使用工具栏将Matplotlib嵌入PySimpleGUI:

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()

我已经看过this question,但我希望使用Matplotlib的工具栏。
甚至this也不起作用,因为在我的例子中plt.get_current_fig_manager()返回None
当从上面的代码打印type(fig_agg)时,我得到

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

其也是X1 M5 N1 X的类型。

  • 顺便说一句,我想到了一个窍门。按下键盘上的p键通常会激活平移模式,所以按下按钮的编程做的伎俩!但这将是不道德的欺骗(:*
avkwfej4

avkwfej41#

我找到了问题的答案。如果能帮到别人,解决方法很简单

fig.canvas.toolbar.pan()

即我们从上述原始调用中去除manager

相关问题