最近做了一个Matlab中的GUI,一个按钮打开选择窗口选择文件,右面一个txt窗口显示选择的文件路径。
结果,双击fig文件在选择完之后显示的时候出错,错误显示为:
Attempt to reference field of non-structure array.
Error in cla>pushbutton1_Callback (line 85)
set(handles.edit1,'string',image_in);
而如果不直接双击运行,而是先进入对应的m文件,从m文件开始运行就不会出错?这是为什么呢?通过搜索,发现了一个靠谱的答案:
(以下转自ilovematlab中文论坛http://www.ilovematlab.cn/thread-74256-1-1.html)
首先,直接运行.fig文件不会执行m文件中的OpeningFcn和CreateFcn。
OpeningFcn函数中有两句至关重要:
% Choose default command line output for **
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
第二句将handles保存在figure对象的“ApplicationData”的一个域名里,创建了figure自己的handles数据。
由于没有执行OpeningFcn,callback函数中的形参handles就失去了意义。可以在每个子函数前面加一行handles = guihandles( gcbf ) ;将figure句柄赋给handles。
再查看对应的m文件:
function cla_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to cla (see VARARGIN)
% Choose default command line output for cla
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
该段代码就是
OpeningFcn
而该段代码是在对应的按钮回调函数的前面,也就是说,直接双击fig文件运行,点击按钮,不会运行该段代码,所以会出错。
那除了从m文件进入运行,还有没其他好办法呢?
我有个思路。可以另外做一个GUI窗口,里面设置个按钮,该按钮的回调函数为上面的那个GUI对应函数。这样,点击该按钮,就相当于从头到尾运行上面的GUI对应的m函数。与从进入m文件运行本质一样。
经测试可用!