use*_*727 3 python user-interface tkinter matplotlib
亲爱的编程共享美,
我正在尝试基于Tkinter和pylab.plot执行"交互式绘图"以绘制1D值.abssissa是1D numpy数组x,ordonates值在多维数组中Y,例如.
import numpy
x = numpy.arange(0.0,3.0,0.01)
y = numpy.sin(2*numpy.pi*x)
Y = numpy.vstack((y,y/2))
Run Code Online (Sandbox Code Playgroud)
我想根据x显示y或y/2(Y矩阵的元素),并在它们之间用左右两个按钮进行切换(为了更复杂的情况).通常我会创建一些如下的函数来绘制图形.
import pylab
def graphic_plot(n):
fig = pylab.figure(figsize=(8,5))
pylab.plot(x,Y[n,:],'x',markersize=2)
pylab.show()
Run Code Online (Sandbox Code Playgroud)
要添加两个按钮来更改n参数的值,我尝试了这个没有成功:
import Tkinter
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
class App:
def __init__(self,master):
# Create a container
frame = Tkinter.Frame(master)
frame.pack()
# Create 2 buttons
self.button_left = Tkinter.Button(frame,text="<",command=self.decrease)
self.button_left.pack(side="left")
self.button_right = Tkinter.Button(frame,text=">",command=self.increase)
self.button_right.pack(side="left")
self.canvas = FigureCanvasTkAgg(fig,master=self)
self.canvas.show()
def decrease(self):
print "Decrease"
def increase(self):
print "Increase"
root = Tkinter.Tk()
app = App(root)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
有人可以帮我理解如何执行这样的功能吗?非常感谢.
要更改线的y值,请保存绘制它时返回的对象(line, = ax.plot(...))然后使用line.set_ydata(...).要重绘图,请使用canvas.draw().
作为基于您的代码的更完整的示例:
import Tkinter
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
class App:
def __init__(self, master):
# Create a container
frame = Tkinter.Frame(master)
# Create 2 buttons
self.button_left = Tkinter.Button(frame,text="< Decrease Slope",
command=self.decrease)
self.button_left.pack(side="left")
self.button_right = Tkinter.Button(frame,text="Increase Slope >",
command=self.increase)
self.button_right.pack(side="left")
fig = Figure()
ax = fig.add_subplot(111)
self.line, = ax.plot(range(10))
self.canvas = FigureCanvasTkAgg(fig,master=master)
self.canvas.show()
self.canvas.get_tk_widget().pack(side='top', fill='both', expand=1)
frame.pack()
def decrease(self):
x, y = self.line.get_data()
self.line.set_ydata(y - 0.2 * x)
self.canvas.draw()
def increase(self):
x, y = self.line.get_data()
self.line.set_ydata(y + 0.2 * x)
self.canvas.draw()
root = Tkinter.Tk()
app = App(root)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)