Help to use Callback property in uicontrol

Hi,
I don't understand how works the 'Callback' property in uicontrol. For example, I create a pushbutton as
pb = uicontrol('Style', 'pushbutton', 'Callback', @fun);
as callback function I need simply an increment of a variable "i" initially i=0; in other words when I click in the pushbutton it should cause increment of "i" by one.
I tried with:
function fun(in)
in=in+1;
end
and so...
pb = uicontrol('Style', 'pushbutton', 'Callback', {@fun, i});
but it doesn't work. Some suggestions ?
Thanks

 채택된 답변

Matt Fig
Matt Fig 2012년 11월 3일

0 개 추천

Where is the variable stored? Callback functions take at least 2 inputs, always. Here is a simple demo, illustrating one way to do what you want. Note that I have made it step by step so you can take the semicolons off to see what is going on in the callback if needed.
function [] = demo_cb()
S.fh = figure('units','pixels',...
'position',[300 300 300 130],...
'menubar','none',...
'name','demo_cb',...
'numbertitle','off',...
'resize','off');
S.pb = uicontrol('style','push',...
'unit','pix',...
'position',[10 20 280 90],...
'string','I=1',...
'fontsize',14,...
'callback',@pb_call);
function [] = pb_call(H,E)
% Callback for pushbutton.
Str = get(H,'string');
Num = regexp(Str,'=','split');
NewNum = str2double(Num{2})+1;
set(H,'string',sprintf('I=%i',NewNum))

댓글 수: 7

Marco
Marco 2012년 11월 3일
Thanks for help!
Who is E ?
Matt Fig
Matt Fig 2012년 11월 3일
편집: Matt Fig 2012년 11월 3일
Like I said, all callbacks take at least two input arguments. The first one is the handle to the calling object, the second one is an eventdata structure that is seldom used. If you want to learn more about GUI making through examples like this, Check out this link:
Also, if your question has been answered, please select the answer.
Marco
Marco 2012년 11월 3일
one last question: how can I putout NewNum variable ?
There are very few types of callbacks that can return a value to the caller. You will need to use a different mechanism.
Marco
Marco 2012년 11월 3일
In your example the callback function is nested, is it? but it not return in the workspace.
In Matt's example the callback function is not nested.
Matt Fig
Matt Fig 2012년 11월 3일
편집: Matt Fig 2012년 11월 3일
Sorry, I stepped away for a while. Walter is correct. The callback is a subfunction (or local function), not a nested function. I usually write GUIs with nested functions when I write them professionally, but using subfunctions is how most people first learn and in some cases it is simpler/preferred.
You can tell at a glance that there are no nested functions in that code because there are no END statements....

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터 및 File Exchange에서 Interactive Control and Callbacks에 대해 자세히 알아보기

제품

질문:

2012년 11월 3일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by