Handles variable in GUIDE is not updating

戏子无情 提交于 2019-12-24 20:36:51

问题


I have a GUI created using MATLAB GUIDE. I am trying to return a value from the GUI. Here are the relevant parts of the code (complete code can be found here):

function varargout = test(varargin)

% --- Outputs from this function are returned to the command line.
function varargout = test_OutputFcn(hObject, eventdata, handles) 

    % Get default command line output from handles structure
    varargout{1} = handles.output;
    varargout{2} = handles.test;


% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)

    handles.test = 'ok';

    % Update handles structure
    guidata(hObject, handles);

And as soon as I execute the GUI, I get this error message:

I found a similar question on the MATLAB newsgroup, but I didn't find a solution (and I read all the guidata's doc, like suggested).

My problem is that I recorded an information in the "handles" structure within one GUIDE's function and I can't retrieve this information in another function.

I tried to un-comment the UIWAIT call in the test_OpeningFcn function in an attempt to wait for the user to close the window.

% --- Executes just before test is made visible.
function test_OpeningFcn(hObject, eventdata, handles, varargin)

    % Choose default command line output for test
    handles.output = hObject;

    % Update handles structure
    guidata(hObject, handles);

    % UIWAIT makes test wait for user response (see UIRESUME)
    uiwait(handles.figure1);

After I click in button, and then try to take the handle variable. But it doesn't work either and fails with a similar error message.

Any help will be welcome. Thanks for your attention.


回答1:


The problem is that when you call the GUI as:

>> [a,b] = test()

this call returns immediately, so in the output function you try to access handles.test which does not exist just yet, causing the error.

There is a screencast by Doug Hull showing how to return a value from a GUI. Here is the list of changes to make copied from that page:

%%% OpenignFCN
uncomment uiwait

%%%OutputFCN
varargout{1} = handles.output;
% The figure can be deleted now
delete(handles.figure1);


%%%CloseReqFCN
if isequal(get(hObject, 'waitstatus'), 'waiting')
    % The GUI is still in UIWAIT, us UIRESUME
    uiresume(hObject);
else
    % The GUI is no longer waiting, just close it
    delete(hObject);
end



回答2:


In the initialization code you have to declare that field.

handles.test = [];

So you can later call it.




回答3:


You need to add in

    handles = guidata(gcf);   

to update handles in different function. Hope im correct.




回答4:


global test
handles.test = 'ok';


来源:https://stackoverflow.com/questions/11851476/handles-variable-in-guide-is-not-updating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!