Behavior of callback function?
2 次查看(过去 30 天)
显示 更早的评论
Hello,
I wanted to break out of a while-loop when a pushbutton is clicked on a figure, so I wrote the code below.
function callbackTest1
uicontrol('Style','pushbutton',...
'String','I''m done...',...
'Position',[100 100 100 100], ...
'Callback','pressed=1');
pressed = 0;
while(1)
if pressed
disp('button pressed')
break
end
pause(0.1)
end
end
But, when I click the pushbutton, 'pressed=1' is displayed on command window and it does not get out of while loop.
In addition, it is suggested that 'disp('button pressed')' part can't be reached which I really don't understand.
On the other hand, the code below works as expected.
The only thing changed is that it's a script, not a function. Everything else is the same.
% callbackTest_script
uicontrol('Style','pushbutton',...
'String','I''m done...',...
'Position',[100 100 100 100], ...
'Callback','pressed=1');
pressed = 0;
while(1)
if pressed
disp('button pressed')
break
end
pause(0.1)
end
Weird thing is that the same suggestion (disp('button pressed') can't be reached) is displayed but it works fine.
Finally, I figured out that I have to write the code like this.
function callbackTest2
uicontrol('Style','pushbutton',...
'String','I''m done...',...
'Position',[100 100 100 100], ...
'Callback',@press);
pressed = 0;
function press(~,~)
pressed = 1;
end
while(1)
if pressed
disp('button pressed')
break
end
pause(0.1)
end
end
1) Why does callbackTest1 not work while callbackTest_script does?
2) In callbackTest1 and callbackTest_script, why can't "disp..." be reached?
3) Anything else I should know about what's behind the behavior of callback function?
4) Is there a better way to do this than callbackTest2?
Thank you.
0 个评论
采纳的回答
Walter Roberson
2020-4-4
'Callback','pressed=1'
Callbacks specified as character vectors are evalin('base') and so only affect the base workspace, not local variables.
You need to use one of the techniques to share variables; Share . Your callbackTest2 is an example of using a shared variable.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Graphics Object Programming 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!