包含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 matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import numpy as np
from 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 once
def 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()