包含Tk嵌入的新答案(与其他答案相比有重大变化,因此添加新答案而不是编辑该答案)。我感动
graph_one()和
graph_two()进开关图包装类,并将其重命名为
draw_graph_one()和
draw_graph_two()。这两个新的类方法替换了
embed_graph_one()和
embed_graph_two()方法。
embed()方法中的大多数内容都是重复的,因此被移动到
config_window()实例化类对象时调用的方法。创建了一些类的数据成员捕捉PLT变量(例如
canvas,
ax,
fig),并创建了一个新的数据成员来跟踪其当前显示图(
graphIndex),以便我们能够正确得出正确的图形时
switch_graphs()被调用(而不是调用
embed_graph_two()每次进行“切换”(如原始代码一样)。(可选)您可以
t从
draw方法中取出并使其成为类数据成员(如果的值
t不变)。
import matplotlibmatplotlib.use("TkAgg")import matplotlib.pyplot as pltimport numpy as npfrom tkinter import *from matplotlib.backends.backend_tkagg import ( FigureCanvasTkAgg, NavigationToolbar2Tk)# Implement the default Matplotlib key bindings.from matplotlib.backend_bases import key_press_handler# Seperated out config of plot to just do it oncedef config_plot(): fig, ax = plt.subplots() ax.set(xlabel='time (s)', ylabel='voltage (mV)',title='Graph One') return (fig, ax)class matplotlibSwitchGraphs: def __init__(self, master): self.master = master self.frame = frame(self.master) self.fig, self.ax = config_plot() self.graphIndex = 0 self.canvas = FigureCanvasTkAgg(self.fig, self.master) self.config_window() self.draw_graph_one() self.frame.pack(expand=YES, fill=BOTH) def config_window(self): self.canvas.mpl_connect("key_press_event", self.on_key_press) toolbar = NavigationToolbar2Tk(self.canvas, self.master) toolbar.update() self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1) self.button = Button(self.master, text="Quit", command=self._quit) self.button.pack(side=BOTTOM) self.button_switch = Button(self.master, text="Switch Graphs", command=self.switch_graphs) self.button_switch.pack(side=BOTTOM) def draw_graph_one(self): t = np.arange(0.0, 2.0, 0.01) s = 1 + np.sin(2 * np.pi * t) self.ax.clear() # clear current axes self.ax.plot(t, s) self.ax.set(title='Graph One') self.canvas.draw() def draw_graph_two(self): t = np.arange(0.0, 2.0, 0.01) s = 1 + np.cos(2 * np.pi * t) self.ax.clear() self.ax.plot(t, s) self.ax.set(title='Graph Two') self.canvas.draw() def on_key_press(event): print("you pressed {}".format(event.key)) key_press_handler(event, self.canvas, toolbar) def _quit(self): self.master.quit() # stops mainloop def switch_graphs(self): # Need to call the correct draw, whether we're on graph one or two self.graphIndex = (self.graphIndex + 1 ) % 2 if self.graphIndex == 0: self.draw_graph_one() else: self.draw_graph_two()def main(): root = Tk() matplotlibSwitchGraphs(root) root.mainloop()if __name__ == '__main__': main()输出(两个窗口,每当单击切换图按钮时交替显示):



