1

Say I have the following function:

function result=myfun(varargin)    
result=[];    
myFig=figure();    
B1=uicontrol(myFig,'Style','pushbutton','String','done','Callback',{@done_Callback});    

    function done_Callback(varargin)  
        result =10;
        delete(mainFig);
    end
end   

I am trying to only return output after the button callback is executed. Right now it returns an empty variable right away. I know how to do this in guide GUIs but all of my project is written without guide. I am assuming I need uiwait somewhere, but not sure where.

0

1 Answer 1

2

The function uicontrol only generates the button, it doesn't wait for it to be pressed. Otherwise, a full GUI with several elements would not be possible – you couldn't insert another element before the first hadn't been activated, and afterwards the first one could not be activated any longer. For this reason, GUI callbacks are executed in another thread than the main Matlab program, namely in the "event queue".

If you want your program to wait until the button is pressed, you have to program this explicitly:

function result=myfun(varargin)    
result=[];    
myFig=figure();    
B1=uicontrol(myFig,'Style','pushbutton','String','done','Callback',{@done_Callback});    
while isempty(result)
    drawnow
end

    function done_Callback(varargin)  
        result =10;
        fprintf('hi\n')
        delete(myFig);
    end
end   

The drawnow is there to tell Matlab it should allocate execution time to the event queue, which is not normally done when Matlab is busy, e.g. with running a while loop.

For (slightly) more information, have a look at How Does a GUI Work? and drawnow.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much. This does exactly what I wanted.
You're welcome. :) I just edited the answer once more, maybe you find the additional information interesting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.